Saturday 26 January 2013

Copy a Directory in VB.NET

Copy a Directory in VB.NET


Copies all folders and files to destination volume/network drive with the same name as the source directory.
    
Sometimes, directory structure is  so nested, at that time u may get following error message.
 Message    "The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."  
Here is the example for copying Inetpub folder to D volume with the same name.

 CopyDirectory("c:\inetpub","d:\")
Shared  Sub CopyDirectory(ByVal src As String, ByVal dest As String)
Try
 
    Dim srcpathroot As String =  Path.GetPathRoot(src)
    Dim destpathroot As String =  Path.GetPathRoot(dest)
 
   'First Create all Directories/Sub directories.
 
    Dim dirs() As String =  Directory.GetDirectories(src,"*",SearchOption.AllDirectories)
    Dim difVolume As String
    For Each difVolume In dirs
 
        Dim path As String =  difVolume.Replace(srcpathroot,destpathroot)
        If Not Directory.Exists(path) Then
            Directory.CreateDirectory(path)
        End If
    Next

'Second Copy all files from Source to Destination with file overwrite.
 
    String()szFiles = Directory.GetFiles(src,"*",SearchOption.AllDirectories)
    Dim srcFile As String
    For Each srcFile In szFiles
        Dim destFile As String =  srcFile.Replace(srcpathroot,destpathroot)
        File.Copy(srcFile, destFile, True)
    Next
 
 
 
Catch ex As Exception
    Console.WriteLine(ex.Message)
End Try
End Sub

Tags:Copy Directory in VB.NET,Folder Copy in VB.NET,Copy a directory to different volume,Copy Folder to USB,Copy folder with same name,Copy Directory in .NET VB.NET,Copy directory to network folder,Copy Directory to UNC folder,Copy Entire Folder,Copy Directory with contents

No comments:

Post a Comment