Using a variable in Getfiles to find files - vb.net

Textbox1.Text = part
'searching the folder with key word from Textbox1'
' Only get files that contain the keyword stored in 'part' string
Dim dirs As String() = Directory.GetFiles("d:\data\", "*$part*")
'display the result
Dim dir As String
For Each dir In dirs
Listbox1.Items.Add(dir)
Next
I can't get it to search the folder for the files that contain the keyword in their name. The keyword is stored in the 'part' variable.

I believe you want to do something like:
Dim dirs As String() = Directory.GetFiles("d:\data\", "*" & part & "*")
This will build the string for the filter based on the part variable.

This is a one-liner:
Listbox1.Items.AddRange(Directory.GetFiles("D:\data\", $"*{Textbox1.Text}*"))

Related

replace text multiple file vb.net

I want multiple files with a name and in a different format
I will replace some of the text
To do this, use the following command:
Dim sb As New StringBuilder(File.ReadAllText("tmp\boot_root\initrd\fstab.*"))
sb.Replace("ro,barrier", "ro,noatime,barrier")
sb.Replace("ro,errors", "ro,noatime,errors")
But this does not work. I need a better command to do this
help please
To get a list of all files matching a pattern in a given directory use Directory.Getfiles(path, pattern). Example:
Dim list as String()
Dim path as String = "C:\tmp\"
Dim filename as String = "fstab"
list = Directory.GetFiles(path, filename & ".*")
For Each file As String In list
'Logic goes here.
Next

Add Subfolder names to Listview

I have Combobox, and I select folder names in It. This folder has to be searched first. In these folders are also folders named "Versions"- and these folders have another folders which I need to add on Listview. I tried this but nothing is added to my Listview:
Dim Folder_To_Search As String() = IO.Directory.GetDirectories("D:\", MyCombo.Text, System.IO.SearchOption.AllDirectories)
For Each folder As String In Folder_To_Search
ListView1.Items.Add(Path.GetFileName(folder + "\Versions\"))
Next
I guess I'm missing something after + "\Versions\", can somebody give me a clue ?
Nothing is being added to your listview because GetDirectories returns, as its name implies, directories. So you're getting your list of directories and then using Path.GetFilename on each of them, but the directories do not have a filename at the end of them so only empty strings are being added to your listview.
Edit for Comment: Then it sounds like you need to run basically two nested directory searches; the first one for folders like "Microsoft" and the second for "Versions" within Microsoft folders, then loop through and get the files:
Dim TopLevelDirectories As String() = IO.Directory.GetDirectories("D:\", "*" & MyCombo.Text & "*", System.IO.SearchOption.AllDirectories)
For Each tlDir As String In TopLevelDirectories
Dim SubLevelDirectories As String() = IO.Directory.GetDirectories(tlDir, "*Versions*", System.IO.SearchOption.AllDirectories)
For Each slDir As String In SubLevelDirectories
Dim dInfo As DirectoryInfo = New DirectoryInfo(slDir)
Dim fInfo() As FileInfo = dInfo.GetFiles
For Each f As FileInfo In fInfo
ListView1.Items.Add(f.FullName) 'or ListView1.Items.Add(f.Name)
Next
Next
Next
If I understand your goal correctly, the code above should find all the files you're looking for. I made some test folders and threw Microsoft/Versions in at different levels of the directories and this code picked them all up

Get count of similar files in a folder

I have a file, lets call it "myFile.txt", in a folder. There are also going to be other files named "myFile1.txt, myFile2.txt, myFile3.txt, myFile4.txt" in that same folder and so forth. I want to check that folder and count how many times "myFile" shows up in that folder no matter what the extension or the number after "myFile". Here's what I have so far, but it's not getting what I want:
Dim MyFiles1() As String = IO.Directory.GetFiles("filepath", "myFile.txt")
I whipped this up and tested it in Visual Studio:
'Get a list of files from a directory you designate
Dim counter As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
counter = My.Computer.FileSystem.GetFiles("C:\YOURDIR")
'Declare your file name
Dim myfile As String = "YOURFILE"
'Create count dim
Dim Occurrences As Integer = 0
'Check all files in the array and check them against our filename
For Each File As String In counter
If File.Contains(myfile) Then
'If a file is found, add +1
Occurrences = Occurrences + 1
End If
Next
'Display total count
MsgBox("number of files is " & Occurrences)
This will go and search the path you designate. It will check all files like your filename in the dir. If it finds one, it will count it. This also checks for case insensitive names as well so you can get all variants of your file name.
Something like below:
Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
' Process the list of files found in the directory.
Dim fileName As String
For Each fileName In fileEntries
' do a simple if statement to see if the file name contains "myFile"
' if so add to some count variable you declare
See here for more reference material on the GetFiles() method (which is the key to solving your issue): https://msdn.microsoft.com/en-us/library/07wt70x2%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Comparing files in list of string to files in target directory

I have searched this issue for 2 days, without finding a solution. I might be using the wrong search terms, due to my limited knowledge of the subject.
I have 2 folders, a source and a target, each with files in them. I need to compare the files in these 2 dirs and delete the duplicate files from the target dir before moving the files from the source dir.
I have created a list of string for both dirs. But I can't seem to figure out how to make the dupes in the targetdir to get deleted instead of from the list itself. However, if I put targetdir or sourcedir in the File.Exists() and File.Delete(), it doesn't see the files.
My code is below. Can anyone help me with this?
Dim sourcedir As String
sourcedir = TextBox1.Text + "\"
Dim targetdir As String
targetdir = readValue + "\"
For Each filename In filelist
If System.IO.File.Exists(filename) Then
System.IO.File.Delete(filename)
End If
Next
Edit:
Thank you so very much. This is the code that I used, in case someone else has the same issue.
Dim sourcedir As String
sourcedir = TextBox1.Text + "\"
Dim targetdir As String
targetdir = readValue + "\"
Dim sourceFilePaths = My.Computer.FileSystem.GetFiles(sourcedir, FileIO.SearchOption.SearchAllSubDirectories)
Dim targetFilePaths = My.Computer.FileSystem.GetFiles(targetdir, FileIO.SearchOption.SearchAllSubDirectories)
'Compare only file names, ignoring paths, and get a list of duplicates.
Dim duplicateFileNames = sourceFilePaths.Select(Function(filePath) System.IO.Path.GetFileName(filePath)).
Intersect(targetFilePaths.Select(Function(filePath) System.IO.Path.GetFileName(filePath)))
'Combine target folder path with duplciate file names and delete each one.
For Each filePath In duplicateFileNames.Select(Function(fileName) System.IO.Path.Combine(targetdir, fileName))
System.IO.File.Delete(filePath)
Application.DoEvents()
Next
E.g.
Dim sourceFolderPath = "C:\SourceFolder"
Dim targetFolderPath = "C:\TargetFolder"
Dim sourceFilePaths = Directory.GetFiles(sourceFolderPath)
Dim targetFilePaths = Directory.GetFiles(targetFolderPath)
'Compare only file names, ignoring paths, and get a list of duplicates.
Dim duplicateFileNames = sourceFilePaths.Select(Function(filePath) Path.GetFileName(filePath)).
Intersect(targetFilePaths.Select(Function(filePath) Path.GetFileName(filePath)))
'Combine target folder path with duplciate file names and delete each one.
For Each filePath In duplicateFileNames.Select(Function(fileName) Path.Combine(targetFolderPath, fileName))
File.Delete(filePath)
Next
Here's an option that doesn't use LINQ:
Dim sourceFolderPath = "C:\SourceFolder"
Dim targetFolderPath = "C:\TargetFolder"
Dim sourceFilePaths = Directory.GetFiles(sourceFolderPath)
Dim targetFilePaths = Directory.GetFiles(targetFolderPath)
Dim sourceFileNames As New List(Of String)
For Each sourceFilePath In sourceFilePaths
sourceFileNames.Add(Path.GetFileName(sourceFilePath))
Next
For Each targetFilePath In targetFilePaths
Dim targetFileName = Path.GetFileName(targetFilePath)
If sourceFileNames.Contains(targetFileName) Then
File.Delete(targetFilePath)
End If
Next
It's important to note that both these examples are case-sensitive. Both the Intersect and Contains methods will accept an IEqualityComparer(Of String) though, so you can provide one to make them case-insensitive.

In vb.net, how do I get files from a directory based on a comma separated string?

I need to create an array() from files in a folder. Here's an example of how I would get all files within a folder.
Dim filesList = New DirectoryInfo("MyPath").GetFiles("*", SearchOption.TopDirectoryOnly).Where(Function(f) Not f.Attributes.HasFlag(FileAttributes.Hidden)).[Select](Function(f) New AClassNameHere(f)).ToArray()
I want to do the exact same thing, but only get files that exist in a comma separated string.
Dim myFiles as String = "filename1.jpg,filename2.jpg,filename3.jpg"
Where you see the AClassNameHere is a class I need to send each file to, and it would also be great if I knew how to send additional data about each file, like its type, size, etc.
Thank you kindly!
You could narrow the query results by adding an additional .Where() filter
Dim myFiles as String = "filename1.jpg,filename2.jpg,filename3.jpg"
Dim filesList = New DirectoryInfo("MyPath")
.GetFiles("*", SearchOption.TopDirectoryOnly)
.Where(Function(f) Not f.Attributes.HasFlag(FileAttributes.Hidden))
.Where(Function(f) myFiles.Contains(f.Name))
.[Select](Function(f) New AClassNameHere(f)).ToArray()
A better option would be to ensure that all filenames follow a pattern.
New DirectoryInfo("MyPath").GetFiles("filename*.jpg", SearchOption.TopDirectoryOnly)
Use this...
Dim Files() As String
Files= filesList.Split(",")
For each File In Files
Msgbox(File)
Next