Copy the entire contents of a directory in C#

前端 未结 22 855
日久生厌
日久生厌 2020-11-22 07:13

I want to copy the entire contents of a directory from one location to another in C#.

There doesn\'t appear to be a way to do this using System.IO class

22条回答
  •  长发绾君心
    2020-11-22 07:33

    Sorry for the previous code, it still had bugs :( (fell prey to the fastest gun problem) . Here it is tested and working. The key is the SearchOption.AllDirectories, which eliminates the need for explicit recursion.

    string path = "C:\\a";
    string[] dirs = Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories);
    string newpath = "C:\\x";
    try
    {
        Directory.CreateDirectory(newpath);
    }
    catch (IOException ex)
    {
        Console.WriteLine(ex.Message);
    }
    for (int j = 0; j < dirs.Length; j++)
    {
        try
        {
            Directory.CreateDirectory(dirs[j].Replace(path, newpath));
        }
        catch (IOException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    
    string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
    for (int j = 0; j < files.Length; j++)            
    {
        try
        {
            File.Copy(files[j], files[j].Replace(path, newpath));
        }
        catch (IOException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    

提交回复
热议问题