【问题标题】:Listen for cmd output and log to file监听 cmd 输出并记录到文件
【发布时间】:2015-08-07 19:13:43
【问题描述】:

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

我知道我需要使用FileSystem,也许还有Process

如果这是可能的,我们将不胜感激。谢谢。

【问题讨论】:

  • 创建一个控制台应用程序。这将满足您的需求。
  • @AbinMathew 我知道要制作一个控制台应用程序,我只是不确定我需要在其中放入什么代码。
  • Console.WriteLine(""); , Console.ReadLine("")

标签: c# cmd listener


【解决方案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 类 MSDN 概述(此页面上有一个快速示例):https://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx

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

【讨论】:

    猜你喜欢
    • 2021-07-24
    • 2015-03-17
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多