Checkout this awesome blog… the author posts all kinds of information related to the new developments at Microsoft…
Daily Archives: November 23, 2008
Recursive File Copier Function
Have you ever had the need for a function to copy every file in a directory… wait no longer… here is a recursive way to copy files:
Sub CopySelectedFiles(ByVal strSourceDirectory As String, ByVal strDestDirectory As String, ByVal strSearchString As String)Dim dirInfo As New DirectoryInfo(strSourceDirectory)Dim fsInfo As FileSystemInfoFor Each fsInfo In dirInfo.GetFileSystemInfosDim strDestFileName As String = Path.Combine(strDestDirectory, fsInfo.Name)If TypeOf fsInfo Is FileInfo And fsInfo.Name.IndexOfAny(strSearchString) > -1 ThenFile.Copy(fsInfo.FullName, strDestFileName, True) ' 'This will overwrite files that already existElse
CopySelectedFiles(fsInfo.FullName, strDestFileName, strSearchString) 'we have found a subdirectory
End IfNext
End Sub
Recursive File Search Code
Below is the first function I’m publishing… It uses my favorite programing feature… recursion. Recursion is a tricky thing to do right. So many loops, so many variables, etc… This function searches for a file and all sub-directories of your root/starter directory.
VB.net Source Code:
Public Function SearchForFile(ByVal strSourceDirectory As String, ByVal strSearchString As String) As StringOn Error Resume NextDim ret As String = ""Dim dirInfo As New DirectoryInfo(strSourceDirectory)Dim fsInfo As FileSystemInfoFor Each fsInfo In dirInfo.GetFileSystemInfosIf TypeOf fsInfo Is FileInfo And _fsInfo.Name.IndexOfAny(strSearchString) > -1 Then
'FOUND IT...
If fsInfo.Name = strSearchString Then'return directory where file is located...
ret = strSourceDirectoryExit ForEnd IfElse
'recurrsively search this sub-folder...
ret = SearchForFile(fsInfo.FullName, strSearchString)If ret <> "" Then Exit ForEnd IfNext
If ret <> "" Then If Right(ret, 1) <> "\" Then ret = ret & "\"SearchForFile = retEnd Function
Programming and Code
My Born-to-Code logo is not just an image on my blog… it is also a tattoo on my left arm. I am very motivated about programming and believe firmly in the notion that a computer should do my work for me. Therefore I’ve decided to share my work with the world… Please feel free to use this code any way you wish… Use it to create programs to give away, to sell, etc… don’t care. Have fun with it. I only ask that you make mention of me somewhere.. about box, read me file.. anything…