有没有cmd回调?

时间:2013-06-03 19:19:00

标签: c#

显然我可以使用Process.Start();

执行cmd控制台的操作

有没有办法获得该流程的输出?例如,我可能会有类似......

Process.Start("sample.bat");

...在我的C#winforms应用程序和sample.bat中将包含类似的内容:

echo sample loaded 

第一个问题:有没有办法在蝙蝠执行后检索sample loaded? 第二个问题:有没有办法在没有弹出控制台窗口的情况下使用它?

3 个答案:

答案 0 :(得分:5)

Process文档中有一个确切如何执行此操作的示例:

// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

答案 1 :(得分:0)

是的,您可以使用

Process.Start(ProcessStartInfo)

有几种方法可以挂钩I / O,包括ProcessStartInfo.RedirectStandardOutput可用。您可以使用这些重载来读取批处理文件的输出。您还可以挂钩Exited事件以了解执行何时完成。

使用CreateNoWindow无窗口。

答案 2 :(得分:0)

process.StartInfo.RedirectStandardOutput设为true并订阅process.OutputDataReceived

using (var process = new Process())
{
    process.StartInfo = new ProcessStartInfo("exename");
    process.StartInfo.RedirectStandardOutput = true;

    process.OutputDataReceived += (s, ev) =>
    {
        string output = ev.Data;
    };


    process.Start();
    process.BeginOutputReadLine();
    process.WaitForExit();
}
相关问题