Finding txt files inside a given folder with subfolders? - vb.net

Can anyone tell me how can I find say *.txt files inside a given folder inside which there are subfolders in the structure 12345\30123\128\txt\100.txt, the main folder can contain other subfolders or txt files but I only want to get the txt files which reside in the subfolders of the format 12345\30123\128\txt\100.txt. i.e. txt files inside all txt folders
I have tried this:
Dim txtFilesArray As String() = Directory.GetFiles(targetDirectory, "*.txt", SearchOption.AllDirectories)
But it gets all txt files?

Dim txtFiles = Directory.EnumerateFiles(targetDirectory,"*.txt",SearchOption.AllDirectories)
.Where(Function(f) f Like "*\#*\#*\#*\txt\#*.txt")
where # matches any digit from 0 to 9 and * matches any 0 or more characters
or slower RegEx version will be something like
Dim txtFiles = Directory.EnumerateFiles(targetDirectory,"*.txt",SearchOption.AllDirectories)
.Where(Function(f) RegEx.IsMatch(f, ".*\\\d+\\\d+\\\d+\\txt\\\\d+\.txt"))
For Each txtFile In txtFiles
'...
Next

This will return all files but those contained at path:
Dim path = "C:\"
Dim di As New DirectoryInfo(path)
Dim files = di _
.GetFiles("*.txt", SearchOption.AllDirectories) _
.Where(Function(info) info.DirectoryName <> path) _
.Select(function(info) info.FullName) _
.ToArray()

Related

Directory.GetFiles | Get only the specific file

I want to copy a specific file only but it copies all files in the directory. Is there any way to achieve it?
here is my code:
Dim dir As DirectoryInfo = New DirectoryInfo("\\SERVER-PC\BrokerDatabase\BrokerDatabase\Attachments")
For Each fi As FileInfo In dir.GetFiles()
fi.CopyTo("D:\" + fi.Name)
Next
It copies all files in the directory because you're looping the .CopyTo without any condition. If the filename of the file you are looking for is static, add a condition with it so it won't copy all the files.
Dim dir As DirectoryInfo = New DirectoryInfo("\\SERVER-PC\BrokerDatabase\BrokerDatabase\Attachments")
For Each fi As FileInfo In dir.GetFiles()
If fi.Name = "FileToBeCopied.txt" Then
fi.CopyTo("D:\" + fi.Name)
End If
Next
Another (fancy) way,
Dim allSeries As IEnumerable(Of String) =
Directory.EnumerateFiles(root, file, SearchOption.AllDirectories)
If allSeries.Count = 0 Then
MsgBox("not found.")
End If
where "root" is a String with the file path, and "file" is a String with the file name

VB.Net - How to Change attributes of Folder included sub folder & files

How to change or remove attribute of selected folder including all sub folders & files.
I used the following code :
System.IO.SetAttribute(FolderBrowserDialog1.SelectedPath,IO.FileAttribute.Hidden)
But it changes only selected folder attributes not sub folders & files
All subfolders and files can be enumerated like this:
If FolderBrowserDialog1.ShowDialog = DialogResult.OK Then
Dim di = New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
di.Attributes = di.Attributes Or FileAttributes.Hidden
For Each i In di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
i.Attributes = i.Attributes Or FileAttributes.Hidden
Next
End If
Another way can be with attrib.exe:
Dim cmd = "attrib +H """ & FolderBrowserDialog1.SelectedPath.TrimEnd("\"c)
Shell("cmd /c " & cmd & """ & " & cmd & "\*"" /S /D", AppWinStyle.Hide)
I expect it to be faster than enumerating all file entries and getting and setting the attributes of each one separately, but another advantage of this method is that by default the shell function does not wait for the command to complete and your program can continue without waiting.
You can loop over subfolder recursively. I think that OS do that recursively too!!
Private Function getAllFolders(ByVal directory As String) As List(of String)
'Create object
Dim fi As New IO.DirectoryInfo(directory)
'Change main folder attribute
System.IO.SetAttribute(directory,IO.FileAttribute.Hidden )
'List to store paths
Dim Folders As New List(Of String)
'Loop through subfolders
For Each subfolder As IO.DirectoryInfo In fi.GetDirectories()
'Add this folders name
Folders.Add(subfolder.FullName)
'Recall function with each subdirectory
For Each s As String In getAllFolders(subfolder.FullName)
Folders.Add(s)
'Change subfolders attribute
System.IO.SetAttribute(s,IO.FileAttribute.Hidden )
Next
Next
Return Folders
End Function

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.

looping inside folders and subfolders .net

Dim txtbx As String = "E:\_net_programs\test"
For Each d As String In Directory.GetDirectories(txtbx)
'For Each di As file
'Next
'MessageBox.Show(d)
'Dim folder As DirectoryInfo in directory
Next
Please help me loop inside this folder "E:_net_programs\test" and open every sub folder
There's the code :
Dim txtbx As String = "E:\_net_programs\test"
For Each File In Directory.GetFiles(txtbx, "*", SearchOption.AllDirectories)
MsgBox(File)
Next
If you don't want a loop of String but of FileInfo to be able to get their attributes (name, parent directory, extension, etc.), there's the code :
Dim txtbx As String = "E:\_net_programs\test"
For Each File As FileInfo In New DirectoryInfo(txtbx).GetFiles("*", SearchOption.AllDirectories)
MsgBox(File.FullName)
Next

How to read files in folders?

I am trying to get my application to check for folders in the folderbrowserdialogs selectedpath and then get those files, but it doesn't work I have tried both listed ways below. The second way gives me an error: (Expression is of type char which is not a collection type)
For Each folder In FileBrowserDialog.SelectedPath
Dim counter As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
counter = My.Computer.FileSystem.GetFiles(folder)
Label1.Text = counter.Count.ToString
Next
For Each folder In FileBrowserDialog.SelectedPath
Dim counter As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
For Each foundfile In folder
counter = My.Computer.FileSystem.GetFiles(foundfile)
Label1.Text = counter.Count.ToString
Next
Any help is appreciated.
FolderBrowserDialog1.SelectedPath will return the path the user selected in the dialog. You still need to write code to go get the files. There may not be a need to get the folders and then files in them. Net has ways to do that for you:
FolderBrowserDialog1.ShowDialog()
Dim myPath As String = FolderBrowserDialog1.SelectedPath
' get all files for a folder
Dim files = Directory.GetFiles(myPath)
' get all files for all sub folders
Dim files = Directory.GetFiles(myPath, "*.*",
System.IO.SearchOption.AllDirectories)
' get certain file types for folder and subs
Dim files = Directory.GetFiles(myPath, "*.jpg",
System.IO.SearchOption.AllDirectories)
You also are not going to be able to simply assign the results to a ReadOnlyCollection like that, because they are ReadOnly. The collection needs to be created/instanced with the complete list:
Dim counter As new ReadOnlyCollection(Of String)(files)