Directory.GetFiles | Get only the specific file - vb.net

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

Related

Finding txt files inside a given folder with subfolders?

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()

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 move all files and folders from current directory to another directory excluding a folder named "My Folder" in vb?

I want to move all files and folders from current directory to another directory excluding a folder named "My Folder". I want to know how can I do this with vb?
Not really tested but might be helpful anyway:
Dim currentDir = Directory.GetCurrentDirectory() ' or whatever you call current
Dim targetDir = Path.Combine(currentDir, "Target-Directory")
Directory.CreateDirectory(targetDir)
Dim allDirs = From dir In Directory.EnumerateDirectories(currentDir, "*.*", SearchOption.AllDirectories)
Where Not Path.GetFileName(dir).Equals("My Folder", StringComparison.InvariantCultureIgnoreCase)
For Each dir As String In allDirs
Try
Dim targetPath As String = Path.Combine(targetDir, Path.GetFileName(dir))
Directory.Move(dir, targetPath)
Catch ex As Exception
' log or whatever, here just ignore and continue ...
End Try
Next
'now move the rest of the files in the troot folder
Dim filesInRoot = From file In Directory.EnumerateFiles(currentDir, "*.*", SearchOption.TopDirectoryOnly)
For Each file As String In filesInRoot
Try
Dim targetPath As String = Path.Combine(targetDir, Path.GetFileName(file))
IO.File.Move(file, targetPath)
Catch ex As Exception
' log or whatever, here just ignore and continue ...
End Try
Next

Combobox just file name (without extention or path) VB.Net

I got the following code which is nice and all however it returns the entire path as well as name
For Each s As String In System.IO.Directory.GetFiles("C:\VTS\TREADSTONE LT\ATC\BASIS\")
combobox1.Items.Add(s)
Next
What I'm after is the file name only and preferably without its extention...
UPDATE
For Each s As String In GetFileNameWithoutExtension("C:\VTS\TREADSTONE LT\ATC\BASIS\")
combobox1.Items.Add(s)
Next
You'll need to use the Path class inside the loop:
Dim dir = "C:\VTS\TREADSTONE LT\ATC\BASIS\"
For Each file As String In System.IO.Directory.GetFiles(dir)
combobox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file))
Next
Change your code to:
For Each s As String In System.IO.Directory.GetFiles("C:\VTS\TREADSTONE LT\ATC\BASIS\")
s = s.Substring(0,s.LastIndexOf("."))
combobox1.Items.Add(s)
Next
Dim di As New IO.DirectoryInfo(My.Application.Info.DirectoryPath + "\softbelldata")
Dim diar1 As IO.FileInfo() = di.GetFiles()
Dim dra As IO.FileInfo
'list the names of all files in the specified directory
For Each dra In diar1
If dra.Extension = ".mdb" Then
txtyear.Items.Add(System.IO.Path.GetFileNameWithoutExtension(dra.Name))
End If
Next

about folder under subfolder using vb.net

i want to delete all the under root folder e:\trichy.root folder contain also sub folder like e:\trichy\chn\20008\20204*.mp3 files. pls help me . always getting an error.
Dim rootfolder1 As FileInfo
rootfolder1 = txtRootFolder.Text
Try
If Directory.Exists(rootfolder1) Then
Dim files() As String = Directory.GetDirectories(rootfolder1)
For Each file As String In files
Dim fi As FileInfo = New FileInfo(file)
If (fi.LastAccessTime < DateTime.Now.AddMonths(-3)) Then
fi.Delete()
display_status("files are deleted successfully")
End If
Next
End If
Catch ex As Exception
display_status("Error in file deletion" & ex.Message)
End Try
pls help me to delete files under this root folder under subfolder?
You don't need the FileInfo objects at all. I have not tested, but it may just be an unnecessary waste or resources, and expensive performancewise.
Try this:
Private Sub DeleteOldFiles(ByVal rootFolder As String, ByVal uptoDate As Date, Optional ByVal fileTypes As String = "*.*")
Try
If Directory.Exists(rootFolder) Then
Dim files() As String = Directory.GetFiles(rootFolder, fileTypes, SearchOption.AllDirectories)
For Each f As String In files
If File.GetLastAccessTime(f) <= uptoDate Then
File.Delete(f)
End If
Next
End If
display_status("files are deleted successfully")
Catch ex As Exception
display_status("Error in file deletion" & ex.Message)
End Try
End Sub
Usage:
DeleteOldFiles(txtRootFolder.Text, Now.AddMonths(-3), "*.mp3")
Deletes the specified directory and, if indicated, any subdirectories and files in the directory.
Directory.Delete(Path1, true)
MSDN
Directory.GetDirectories returns all sub-directories. Then you're creating FileInfo objects from it.
I assume that you instead want to delete the files in that folder, than you need to use Directory.GetFiles:
Dim files() As String = Directory.GetFiles(rootfolder1)
For Each file As String In files
Dim fi As FileInfo = New FileInfo(file)
If (fi.LastAccessTime < DateTime.Now.AddMonths(-3)) Then
fi.Delete()
End If
Next
display_status("files are deleted successfully")
If you want to delete all files in all sub-folders recursively:
Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
Dim fileName As String
For Each fileName In fileEntries
Dim fi As FileInfo = New FileInfo(fileName)
If (fi.LastAccessTime < DateTime.Now.AddMonths(-3)) Then
fi.Delete()
End If
Next fileName
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
' Recurse into subdirectories of this directory.
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
ProcessDirectory(subdirectory)
Next subdirectory
End Sub
You would call it:
ProcessDirectory(rootfolder1)