繁体   English   中英

重定向运行Shell命令的Process的输出时,C#Logfile始终为空

[英]C# Logfile is always blank when redirecting output of Process that runs Shell Commands

我在下面的代码中使用DevCon.exe捕获内容并将其写入文件中。 我解析这个文件是为了需要。

Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C devcon.exe find = port *monitor* >> monitor_Details.txt";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.Verb = "runas";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.Start();
p.WaitForExit();

StreamReader sr = p.StandardOutput;
string log = sr.ReadToEnd();
StreamWriter sw = p.StandardInput;
sw.WriteLine("hi.txt");
p.Close();

在这里,我看到txt文件一直是空白的。 没有任何内容写入文本文件。 有什么问题吗? 我还检查了分配给的变量日志

sr.ReadToEnd()

即便如此,日志始终是空白的。

Pl帮助shell命令无法执行的原因:

port *monitor* >> monitor_Details.txt

Process对象中的CMD shell输出重定向不能像它在控制台shell中的工作方式那样工作。 ">>""|" 在Process上下文中不起作用。

您需要直接在Process对象中运行devcon.exe而不是在CMD.EXE下包装。 然后从Process对象的缓冲区捕获输出,并将其保存到txt文件中(如果需要日志)。 只需将您的必要参数作为“ find = port *monitor* ”传递,就像您在示例中所做的那样。

MSDN有关于输出缓冲区捕获的详细示例和最佳实践。 在这里阅读 在这里

我有一个类似的程序,但将输出重定向到我的应用程序的面板。

我想补充一下

            P.EnableRaisingEvents = true;
            P.OutputDataReceived += proc_OutputDataReceived;
            P.ErrorDataReceived  += proc_ErrorDataReceived;

            P.Start();

            P.BeginOutputReadLine();
            P.BeginErrorReadLine();

这意味着您可以从缓冲区中读取数据,并可以选择将其重定向到文件

    void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        //e.Data contains the console output. You can redirect it where ever you like
    }

希望能帮助到你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM