【问题标题】:Get Values from Process StandardOutput从流程标准输出中获取值
【发布时间】:2013-02-22 20:26:43
【问题描述】:

我正在尝试获取输出以显示我机器上当前打开的文档,但无论如何它都会返回 NULL。

StringCollection values = new StringCollection();
var proc = new Process
{
     StartInfo = new ProcessStartInfo
     {
          FileName = "openfiles.exe",
          Arguments = "/query /FO CSV /v",
          UseShellExecute = false,
          RedirectStandardOutput = true,
          CreateNoWindow = true
     }
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
     string line = proc.StandardOutput.ReadLine();
     values.Add(line);
}
foreach (string sline in values)
MessageBox.Show(sline);

编辑:

在进一步审查期间,我发现我遇到了异常问题。在我的诊断运行期间,我得到以下信息: Proc.BasePriority 出现 System.InvalidOperationException 类型的异常

编辑:

尝试将代码拉取为:

string val = proc.StandardOutput.ReadToEnd();
MessageBox.Show(val);

返回时也是一个 NULL 值,即使在 proc.start(); 之后,Proc 仍然有错误。

【问题讨论】:

  • 您确定该进程确实启动并运行了吗?也可以尝试 compiler.StandardOutput.ReadToEnd() 而不是循环直到 EndOfStream。
  • 这也返回一个 NULL 值。字符串 val = proc.StandardOutput.ReadToEnd(); MessageBox.Show(val);

标签: c# wpf .net-4.0


【解决方案1】:

您必须同时读取标准输出和标准错误流。这是因为您无法从同一个线程中同时读取它们。

要实现这一点,您必须使用将在单独线程上调用的eventhandlers

将代码编译为anycpu,因为openfiles 有 32 位和 64 位版本。如果架构不匹配,它可能找不到可执行文件。

从错误流中读取的行前面带有 ! > 所以他们在输出中脱颖而出。

    StringCollection values = new StringCollection();
    var proc = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "openfiles.exe",
            Arguments = "/query /FO CSV /v",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = false
        }
    };
    proc.Start();

    proc.OutputDataReceived += (s,e) => {
        lock (values)
        {
            values.Add(e.Data);
        }
    };
    proc.ErrorDataReceived += (s,e) => {
        lock (values)
        {
            values.Add("! > " + e.Data);
        }
    };

    proc.BeginErrorReadLine();
    proc.BeginOutputReadLine();

    proc.WaitForExit();
    foreach (string sline in values)
        MessageBox.Show(sline);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2016-11-17
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    相关资源
    最近更新 更多