+ Reply to Thread
Results 1 to 4 of 4

Thread: How to Copy folder

  1. #1
    Junior Member
    Join Date
    Dec 2011
    Posts
    2

    How to Copy folder

    Is there a function I can call in C# that will copy folders?

  2. #2
    Junior Member Peter's Avatar
    Join Date
    Dec 2011
    Location
    CA
    Posts
    5
    C# does not have one function call to copy the entire folder. You will need to write this function yourself. I have code already that you can use if you want. Just do your own testing before using it in your app.

    // Copy all folders and files including sub-folders
    public static void copyFolder(string sourceDir, string destDir)
    {

    if (!Directory.Exists(sourceDir))
    throw new Exception("The source directory " + sourceDir + " does not exist");

    if (!Directory.Exists(destDir))
    Directory.CreateDirectory(destDir);

    foreach (string file in Directory.GetFiles(sourceDir))
    {
    File.Copy(file, destDir + "\\" + Path.GetFileName(file), true);
    }

    foreach (string dir in Directory.GetDirectories(sourceDir))
    {
    copyFolder(dir, destDir + "\\" + Path.GetFileName(dir)); // This is recursive call
    }
    }

  3. #3
    Junior Member
    Join Date
    Dec 2011
    Posts
    2
    Thanks Peter. This code works great.

  4. #4
    Junior Member Peter's Avatar
    Join Date
    Dec 2011
    Location
    CA
    Posts
    5
    No problem. Here is the opposite code to delete folder if ever needed.

    //// How to delete all folders and files including sub folders in C# ////

    public static void DeleteDirectory(String dir)
    {

    if (Directory.Exists(dir))
    {
    foreach (string f in Directory.GetFiles(dir))
    {
    File.Delete(f);
    }

    foreach (string d in Directory.GetDirectories(dir))
    {
    DeleteDirectory(d); // This is the Recursive Call
    Directory.Delete(d);
    }
    }


    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts