Farkas Bence Farkas Bence - 1 year ago 109
C# Question

run batch file xcopy from .NET (C#) and get the result

I have a simple batch file:

xcopy source1 dest1
xcopy source2 dest2

I would like to run this from a .NET application, and get the result of the process (as far as I know xcopy returns 0 on success and 1 on fail), to check whether it was successful (both files copied) or not. How can I do that?


Answer Source

There are three questions in this

  1. How do I execute an external command
  2. How to receive the output
  3. How do I parse the result

1: Running a DOS - Command is pretty easy:

System.Diagnostics.Process.Start("xcopy","source1 dest1");

2: Now you have two possibilities to retrieve the output. The first is to change your command to "xcopy source1 dest1 >output.txt" and read the txt-file afterwards. The second is to run the thread differently:

var proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "xcopy",
        Arguments = "source1 dest1",
        RedirectStandardOutput = true
string response=string.Empty;
while (!proc.StandardOutput.EndOfStream) {
    response += proc.StandardOutput.ReadLine();

now response contains the response of your copy command. Now all you have to do is to parse the return value (3).

If you got problems with the last part, search on SO or write a new question for it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download