简体   繁体   中英

Copy file from one directory to another using cmd in C#

I need to copy a file from one directory to another and do something with that file. I need to copy it with cmd , rather than File.Copy() , because I need the copy to be done as a part of ProcessStartInfo .

You can use this code and change startInfo.Arguments , but /C should be!

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new 
System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C copy example.txt backup.txt";
process.StartInfo = startInfo;
process.Start();

You can create a bat-file to copy one or multiple files (using *). Then execute the batch file.

        string batFileName = @"C:\{filePath}\copy.bat";
        System.IO.File.WriteAllText(batFileName, @"copy {fileName}.{extension} {destination-filePath}");
        System.Diagnostics.Process.Start(batFileName);

I was able to formulate this answer using the DOS Copy syntax along with this Stack Overflow QA Start cmd window and run commands inside

var startInfo = new ProcessStartInfo {
    FileName = "cmd.exe",
    RedirectStandardInput = true,
    RedirectStandardOutput = true,
    UseShellExecute = false,
    CreateNoWindow = true
};

var process = new Process {StartInfo = startInfo};
process.Start();
process.StandardInput.WriteLine(@"copy c:\Source\Original.ext D:\Dest\Copy.ext");
process.StandardInput.WriteLine("exit");
process.WaitForExit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM