wpf 从流程标准输出中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15032643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Values from Process StandardOutput
提问by Jesse
I am attempting to get output to show the currently open documents on my machine, but it comes back NULL no matter what.
我试图获得输出以显示我机器上当前打开的文档,但无论如何它都会返回 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);
Edit:
编辑:
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
在进一步期间,我发现我遇到了异常问题。在我的诊断运行期间,我得到以下信息: Proc.BasePriority thre an exception of type System.InvalidOperationException
Edit:
编辑:
Attempted to pull code as:
尝试将代码拉为:
string val = proc.StandardOutput.ReadToEnd();
MessageBox.Show(val);
Also a NULL value on return, and Proc still had errors even after proc.start();.
返回时也是 NULL 值,即使在 proc.start(); 之后,Proc 仍然有错误。
回答by rene
You have to read both the standard output and standard error streams. This is because you can't read them both from the same thread.
您必须阅读标准输出和标准错误流。这是因为您不能从同一个线程中读取它们。
To achieve this you have to use the eventhandlersthat will be called on a separate thread.
为此,您必须使用将在单独线程上调用的事件处理程序。
Compile the code as anycpuas openfilescomes in a 32-bit and 64-bit variant. It might not find the executable if there is an architecture mismatch.
编译代码anycpu作为openfiles采用的是32位和64位变体。如果体系结构不匹配,它可能找不到可执行文件。
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);

