Petar
Petar

Reputation: 331

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.

Upvotes: 5

Views: 4291

Answers (3)

Mad Myche
Mad Myche

Reputation: 1075

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();

Upvotes: 1

AsusT9
AsusT9

Reputation: 154

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);

Upvotes: 2

PWND
PWND

Reputation: 439

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();

Upvotes: 5

Related Questions