Copy the entire contents of a directory in C#

前端 未结 22 1067
日久生厌
日久生厌 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:43

    A minor improvement on d4nt's answer, as you probably want to check for errors and not have to change xcopy paths if you're working on a server and development machine:

    public void CopyFolder(string source, string destination)
    {
        string xcopyPath = Environment.GetEnvironmentVariable("WINDIR") + @"\System32\xcopy.exe";
        ProcessStartInfo info = new ProcessStartInfo(xcopyPath);
        info.UseShellExecute = false;
        info.RedirectStandardOutput = true;
        info.Arguments = string.Format("\"{0}\" \"{1}\" /E /I", source, destination);
    
        Process process = Process.Start(info);
        process.WaitForExit();
        string result = process.StandardOutput.ReadToEnd();
    
        if (process.ExitCode != 0)
        {
            // Or your own custom exception, or just return false if you prefer.
            throw new InvalidOperationException(string.Format("Failed to copy {0} to {1}: {2}", source, destination, result));
        }
    }
    

提交回复
热议问题