Auto Ad Code

Wednesday, June 6, 2012

Copy Directory without using Directory.Move [SOLVED]

Following function will copy a directory/folder from one place to another without using Directory.Move.
Q: Why we need following function if Directory.Move is there?
A: Because Directory.Move expires(deletes) the session whenever you use it.

VB


Private Sub CopyDirectory(pSourcePath As String, pDestinationPath As String)
        For Each dirPath As String In Directory.GetDirectories(pSourcePath, "*", SearchOption.AllDirectories)
            Directory.CreateDirectory(dirPath.Replace(pSourcePath, pDestinationPath))
        Next

        For Each newPath As String In Directory.GetFiles(pSourcePath, "*.*", SearchOption.AllDirectories)
            File.Copy(newPath, newPath.Replace(pSourcePath, pDestinationPath))
        Next
    End Sub


C#

    private void CopyDirectory(string pSourcePath, string pDestinationPath)
{
       foreach (string dirPath in Directory.GetDirectories(pSourcePath, "*", SearchOption.AllDirectories)) {
              Directory.CreateDirectory(dirPath.Replace(pSourcePath, pDestinationPath));
       }

       foreach (string newPath in Directory.GetFiles(pSourcePath, "*.*", SearchOption.AllDirectories)) {
              File.Copy(newPath, newPath.Replace(pSourcePath, pDestinationPath));
       }
}

No comments:

Post a Comment