-1

After seeing a youtube video I tested this code:

string cmd1 = @"xcopy c:\A\*.* c:\b";
Process ps = new Process();
ps.StartInfo.FileName = "cmd.exe";
ps.StartInfo.CreateNoWindow = true;
ps.StartInfo.RedirectStandardInput = true;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.UseShellExecute = false;
ps.Start();
ps.StandardInput.WriteLine(cmd1);
ps.StandardInput.Flush();
ps.StandardInput.Close();
ps.WaitForExit();
Console.WriteLine(ps.StandardOutput.ReadToEnd());

The command is executed but i see no output. What do i need to do to make visible the cmd window and the command output? Thanks

gtpt
  • 113
  • 7
  • Do you want to show the console window and the output in it or do you want to hide it? – thatguy Jul 02 '20 at 08:28
  • I was curiouse about showing the console window and the output in it. Just like if i was using the command line. – gtpt Jul 03 '20 at 15:36

1 Answers1

2

If you want to execute your command in the cmd.exe window, you can do it like this.

var process = new Process();
var startInfo = new ProcessStartInfo
{
    FileName = "cmd.exe",
    Arguments = @"/K xcopy c:\A\*.* c:\b"
};

process.StartInfo = startInfo;
process.Start();

Note that /K keeps the command line window open, replace it with /C to automatically close it after copying.

If you want to start xcopy without showing the console window and collecting the output to show it where you want, use this.

var process = new Process();
var startInfo = new ProcessStartInfo
{
    WindowStyle = ProcessWindowStyle.Hidden,
    FileName = "xcopy",
    Arguments = @"c:\A\*.* c:\b",
    RedirectStandardOutput = true
};

process.StartInfo = startInfo;
process.Start();

var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();

// Print the output to Standard Out
Console.WriteLine(output);

// Print the ouput to e.g. Visual Studio debug window
Debug.WriteLine(output);

Note that this only works as expected, if your B folder exists folder does not already contain any of your files. Otherwise, the window will stay open, because you are asked, whether the directory should be created and the files should be overwritten. To not overcomplicate this by writing input, you could use the following arguments for xcopy.

Arguments = @"c:\A\*.* c:\b\ /Y /I"

The /Y switch will overwrite files without asking and /I will create a non-existing directory. It is mandatory for this to work to have a trailing backslash on your destination directory path (c:\b\ instead of c:\b).

thatguy
  • 21,059
  • 6
  • 30
  • 40