从WPF应用程序运行命令行命令

时间:2020-07-01 21:18:06

标签: wpf command-line

看到youtube视频后,我测试了以下代码:

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

命令已执行,但我看不到任何输出。 我需要怎么做才能使cmd窗口和命令输出可见? 谢谢

1 个答案:

答案 0 :(得分:1)

如果要在cmd.exe窗口中执行命令,则可以这样做。

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

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

请注意,/K使命令行窗口保持打开状态,将其替换为/C可以在复制后自动将其关闭。

如果要启动xcopy而不显示控制台窗口并收集输出以将其显示在所需的位置,请使用它。

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

请注意,如果您的B文件夹存在文件夹尚未包含您的任何文件,则此操作只能按预期进行。否则,该窗口将保持打开状态,因为会询问您是否应该创建目录以及是否应覆盖文件。为了不因编写输入而使操作复杂化,可以对xcopy使用以下参数。

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

/Y开关将覆盖文件而不会询问,/I将创建一个不存在的目录。为此,必须在目标目录路径( c:\ b \ 而不是 c:\ b )上使用反斜杠。