Monday, May 10, 2010

Copy files and folder from source location to destination location

Copy files/folders from old folder to new Folder recursively.
private static void MoveAll(string pobjSource, string pobjTarget)
{
// Check if the target directory exists, if not, create it.
if (Directory.Exists(pobjTarget) == false)
{
Directory.CreateDirectory(pobjTarget);
}
foreach (string filename in Directory.GetFiles(pobjSource, "*.*"))
{
File.Copy(filename, Path.Combine(pobjTarget, Path.GetFileName(filename)));
}
// Copy each subdirectory using recursion.
foreach (string objSourceSubDir in Directory.GetDirectories(pobjSource))
{
MoveAll(objSourceSubDir, Path.Combine(pobjTarget, Path.GetFileName(objSourceSubDir)));
}
}

4 comments:

  1. Following line can be changed to move only specific file.

    Directory.GetFiles(pobjSource, "*.*")

    Lets say if i want to move files whose name contains "test" then it will be like this...

    Directory.GetFiles(pobjSource, "*test*.*")

    ReplyDelete
  2. I tried your code and it didn't move anything. It only made a copy.

    ReplyDelete
  3. Yes it is for copying file from one location to another.

    Actually i need to change the heading of this post :).

    ReplyDelete
  4. If you want to copy files, it is better to use a recursive method so that you can define whether files inside a sub-directory can be copied or not.

    ReplyDelete