监听cmd输出和日志到文件
本文关键字:文件 日志 cmd 输出 监听 | 更新日期: 2023-09-27 18:06:50
我正在尝试制作一个c#程序,可以侦听和输出到cmd.exe并将其记录到文件中。例如,如果我运行一个exe,它在cmd中运行一个命令,如echo "hello"
,我希望echo "hello"
被写入一个文件。
我知道我需要使用FileSystem
,以及Process
可能?
如果这是可能的,帮助将真的很感激。谢谢。
下面是一个简短的示例。有很多这样的例子,我会试着在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()的示例:StandardOutput.ReadToEnd()挂起