从过程中获取值StandardOutput [英] Get Values from Process StandardOutput
问题描述
我试图让输出显示在我的机器上当前打开的文档,但它回来了NULL不管是什么。
I am attempting to get output to show the currently open documents on my machine, but it comes back NULL no matter what.
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 THRE的异常类型System.InvalidOperationException的
During further review I see that I am getting an exception issue. During my diag run I get the following: Proc.BasePriority thre an exception of type System.InvalidOperationException
编辑:
试图去拉code为:
string val = proc.StandardOutput.ReadToEnd();
MessageBox.Show(val);
另外一个NULL值的回报,PROC仍然有错误,甚至proc.start后();
Also a NULL value on return, and Proc still had errors even after proc.start();.
推荐答案
您已经阅读了标准误差和错误流。因为你不能同时在同一个线程读取它们,你必须USDE异步方法和的事件处理器。 当我运行此code我看到openFiles散只能在32位OS-ES运行。从错误流中读取的行是prepended有! >让他们脱颖而出的输出。
You have to read both standard error and error streams. Because you can't read them both from the same thread you have to usde the async methods and eventhandlers. When I run this code I see that openfiles can only be run on 32 bits OS-es. The lines that are read from the error stream are prepended with ! > so they stand out in the output.
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);
这篇关于从过程中获取值StandardOutput的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!