about folder under subfolder using vb.net - 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)

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

How to check if a file/folder exists in the C drive VB.NET

i'm trying to create a simple anti-cheat which detects external cheats in all the C drive, but i don't know how to check if a determinate file exists in all the C drive, any help?
Here is code that I adapted from How to: Iterate Through a Directory Tree. In the example, the FileExists() function returns True if the file bit32.txt is found anywhere on the C drive. Not all files and directories may be accessible. In that case, the function display the paths of these files and directories. You may want to adapt the code to do whatever you want in these cases.
Imports System.IO
Module Module1
Private Sub Main(ByVal args() As String)
Dim exists As Boolean = FileExists(New DriveInfo("C").RootDirectory, "bit32.txt")
End Sub
Private Function FileExists(ByVal root As DirectoryInfo, ByVal filename As String) As Boolean
Dim files() As FileInfo = Nothing
Dim subDirs() As DirectoryInfo = Nothing
' First, process all the files directly under this folder
Try
files = root.GetFiles("*.*")
Catch e As Exception
' This code just writes out the message and continues to recurse.
' You may decide to do something different here. For example, you
' can try to elevate your privileges and access the file again.
Console.WriteLine(e.Message)
End Try
If (Not (files) Is Nothing) Then
For Each fi As FileInfo In files
' In this example, we only access the existing FileInfo object. If we
' want to open, delete or modify the file, then
' a try-catch block is required here to handle the case
' where the file has been deleted since the call to TraverseTree().
'Console.WriteLine(fi.FullName);
If (fi.Name = filename) Then
Return True
End If
Next
End If
Try
' Now find all the subdirectories under this directory.
subDirs = root.GetDirectories
For Each dirInfo As DirectoryInfo In subDirs
' Resursive call for each subdirectory.
If FileExists(dirInfo, filename) Then
Return True
End If
Next
Catch e As Exception
' This code just writes out the message and continues to recurse.
' You may decide to do something different here. For example, you
' can try to elevate your privileges and access the file again.
Console.WriteLine(e.Message)
End Try
Return False
End Function
End Module
You can have an extension on DirectoryInfo that non-recursively iterates through the root directory looking for files.
<Extension()>
Public Iterator Function GetFilesDepthFirst(ByVal root As DirectoryInfo, ByVal Optional dirPattern As String = "*", ByVal Optional filePattern As String = "*.*") As IEnumerable(Of FileInfo)
Dim stack = New Stack(Of DirectoryInfo)()
stack.Push(root)
While stack.Count > 0
Dim current = stack.Pop()
Dim files = Enumerable.Empty(Of FileInfo)()
Dim dirs = Enumerable.Empty(Of DirectoryInfo)()
Try
dirs = current.EnumerateDirectories(searchPattern:=dirPattern)
files = current.EnumerateFiles(searchPattern:=filePattern)
Catch ex1 As UnauthorizedAccessException
Catch ex2 As PathTooLongException
End Try
For Each file As FileInfo In files
Yield file
Next
For Each dir As DirectoryInfo In dirs
stack.Push(dir)
Next
End While
End Function
You could then call it fairly easily like this:
Dim dInfo = New DirectoryInfo("C:\")
Dim matches = dInfo.GetFilesDepthFirst(filePattern:="somefile.dll")
Dim exists = matches.Any()
Also, the more specific you are at the starting directory, the quicker it will run. Usually searching from the root of C:\ is a very slow and bad idea.

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

Creating a list of all directory

I'm trying to create a list of all directories and their sub-directories in a given path in visual studio 2012.
It's a very long time since I've been in touch with visual basic. I hope somebody can show a simple way for this task.
Any kind of help is much appreciated. :)
In the System.IO namespace
Directory.GetDirectories(string, string, SearchOptions)
A good example from MSDN
Dim dirs As String() = Directory.GetDirectories("c:\", "*.*", SearchOption.AllDirectories)
Console.WriteLine("The number of directories starting with p is {0}.", dirs.Length)
Dim dir As String
For Each dir In dirs
Console.WriteLine(dir)
Next
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
However keep in mind that some directories could have particular access permissions and your code could fail with an IOException. (That's particularly true for the system directories)
Another option is through the use of Directory.EnumerateDirectories that is preferable when you work with many directories and you don't need to have the string array with names filled.
EnumerateDirectories start immediately without waiting to filling the array and is very useful in situation where your code loops over the enumeration
For Each dirName in Directory.EnumerateDirectories("C:\", "p*", SearchOptions.AllDirectories)
..... do something with the directory here ....
Next
Dim path as string ="c:\DirectoryTest"
Dim result = Directory.EnumerateDirectories(path, "*", System.IO.SearchOption.AllDirectories)
This recursive method will get all directories & its sub-directories from a given path:
Option 1#
Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
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
Option 2#
Module Module1
Sub Main()
Try
Dim dirPath As String = "c:\\myDirctory"
Dim dirs As List(Of String) = New List(Of String)(Directory.EnumerateDirectories(dirPath))
For Each folder In dirs
Console.WriteLine("{0}", folder.Substring(folder.LastIndexOf("\") + 1))
Next
Console.WriteLine("{0} directories found.", dirs.Count)
Catch UAEx As UnauthorizedAccessException
Console.WriteLine(UAEx.Message)
Catch PathEx As PathTooLongException
Console.WriteLine(PathEx.Message)
End Try
End Sub
End Module
You can refer MSDN for further details:
http://msdn.microsoft.com/en-us/library/c1sez4sc.aspx
http://msdn.microsoft.com/en-us/library/dd383304.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2