侦听cmd输出并记录到文件

时间:2015-08-07 19:13:44

标签: c# cmd listener

我正在尝试创建一个可以侦听并输出到cmd.exe并将其记录到文件的C#程序。例如,如果我运行一个exe并且它在echo "hello"之类的cmd中运行一个命令,我想将echo "hello"写入文件中。

我知道我需要使用FileSystem以及Process吗?

如果这是可能的,那么真的很感激帮助。感谢。

1 个答案:

答案 0 :(得分:1)

这是一个应该有用的快速小例子。那里有很多例子,我会尝试查看stackoverflow并发布一个...

    string cmd_to_run = "dir"; // whatever you'd like this to be...

    // set up our initial parameters for out process
    ProcessStartInfo p_info = new ProcessStartInfo();
    p_info.FileName = "cmd";
    p_info.Arguments = "/c " + cmd_to_run;
    p_info.UseShellExecute = false;

    // instantiate a new process
    Process p_to_run = new Process();
    p_to_run.StartInfo = p_info;

    // wait for it to exit (I chose 120 seconds)
    // waiting for output here is not asynchronous, depending on the task you may want it to be
    p_to_run.Start();
    p_to_run.WaitForExit(120 * 1000);

    string output = p_to_run.StandardOutput.ReadToEnd();  // here is our output

以下是Process class MSDN概述(此页面上有一个快速示例):https://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx

这是一个处理在进程上调用ReadToEnd()的示例:StandardOutput.ReadToEnd() hangs