logo VB.Net - Working With Directories
Guide Contents
DigitalDan Home Page

Notes

 
List Sub Folders in Folder (Not Recursive)
Private Function ListDirectories(folder As String) As ListFilesError
' Top level only
' initialise results
Dim ret As ListFilesError
ret.ListFiles = New List(Of String) From {folder}
ret.ErrorMessage = ""
Try
ret.ListFiles.AddRange(IO.Directory.GetDirectories(folder))
Catch ex As Exception
ret.ErrorMessage = ex.Message
ret.ListFiles.Clear()
End Try
Return ret
End Function

 
List Sub Folders in Folder and Sub Folders
Private Function ListDirectories1(folder As String, Optional IgnoreSystemFiles As Boolean = True) As ListFilesError
' Include nested sub directories
' initialise results
Dim ret As ListFilesError
ret.ListFiles = New List(Of String) From {folder}
ret.ErrorMessage = ""
' for each folder in list - add all subfolders
Dim i As Integer = 0
While i < ret.ListFiles.Count
Try
If (Not IgnoreSystemFiles) OrElse (Not IsSystemFile(ret.ListFiles.Item(i))) Then
ret.ListFiles.AddRange(IO.Directory.GetDirectories(ret.ListFiles.Item(i)))
End If
Catch ex As Exception
If ex.Message.ToLower.Contains("access to the path") Then
i += 1
Continue While
Else
ret.ErrorMessage = ex.Message
ret.ListFiles.Clear()
Exit While
End If
End Try
i += 1
End While
Return ret
End Function

 
Commands For Manipulating Directories
Dont forget to use Try...Catch...Blocks. You may need a backgroundworker - especially if user cas any control over teh selected directories.
 
In these examples, the variables should be assigned as follows....
oldDirectory = string containing name of existing directory to be copied
newDirectory = string conatining the directory name of the directory that will be created
overwrite = boolean. If true and file already exists,it will be overwritten. If false an exiting file would cause an error
dirOption = either FileIO.DeleteDirectoryOption.DeleteAllContents or FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty the first will delete non-empty directories but the second throws an error.
 
My.Computer.FileSystem.CopyDirectory(oldDirectory, newDirectory, overwrite)
My.Computer.FileSystem.CreateDirectory(newDirectory)
My.Computer.FileSystem.DeleteDirectory(oldDirectory, dirOption)
Dim DirectoryExists As Boolean = My.Computer.FileSystem.DirectoryExists(oldDirectory)
My.Computer.FileSystem.MoveDirectory(oldDirectory, newDirectory, overwrite)
My.Computer.FileSystem.RenameDirectory(oldDirectory, newDirectory)

 

DigitalDan.co.uk ... Hits = 196