从流程标准输出中获取值 [英] 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 引发 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
尝试将代码拉为:
string val = proc.StandardOutput.ReadToEnd();
MessageBox.Show(val);
返回时也是 NULL 值,即使在 proc.start(); 之后 Proc 仍然有错误.
Also a NULL value on return, and Proc still had errors even after proc.start();.
推荐答案
您必须同时阅读标准输出和标准错误流.这是因为你不能从同一个线程中读取它们.
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 eventhandlers that will be called on a separate thread.
将代码编译为 anycpu
,因为 openfiles
有 32 位和 64 位变体.如果架构不匹配,它可能找不到可执行文件.
Compile the code as anycpu
as openfiles
comes in a 32-bit and 64-bit variant. It might not find the executable if there is an architecture mismatch.
从错误流中读取的行以 !> 所以他们在输出中脱颖而出.
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);
这篇关于从流程标准输出中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!