【发布时间】:2015-07-13 17:47:21
【问题描述】:
我在我的应用程序中收到控制台输出。我使用来自here 的代码(公认的解决方案)。 但我从来没有在我的 OutputDataReceived 中得到 null。相反,我在输出的末尾有 String.Empty。 使用 String.NullOrEmpty 而不是仅与 null 进行比较是否正确?
static void Main(string[] args)
{
var command = @"wmic cpu get loadpercentage";
using (Process process = new Process())
{
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardError = true;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
process.OutputDataReceived += (sndr, a) =>
{
if (a.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(a.Data);
}
};
process.ErrorDataReceived += (sndr, a) =>
{
if (a.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(a.Data);
}
};
process.Start();
process.BeginOutputReadLine();
outputWaitHandle.WaitOne();
string path = "Test.txt";
using (StreamWriter sw = File.Exists(path) ? File.AppendText(path) : File.CreateText(path))
{
sw.WriteLine(String.Format("{0}, {1}", DateTime.Now, output));
}
}
}
}
更新: 多行输出好像不行。问题是为什么 a.Data 中没有 null
【问题讨论】:
-
你应该总是在最后得到一个
null。您没有收到它的原因是您没有等待进程终止。您需要在process.Start()之后的某个位置使用process.WaitForExit()(特别是在进程在调用BeginOutputReadLine之前退出的情况下)。 -
@Cameron 但我的进程 (cmd.exe) 永远不会退出。我想使用 process.StandardInput.WriteLine 键入多个命令并接收相应的输出
-
您发布的代码设置后没有使用命令变量,您的新进程可能什么都不做
-
如果进程永远不会退出,那么它的标准输出将保持打开状态(默认情况下,无论如何),您将永远不会收到 null。您究竟想通过这些自动重置事件来完成什么?
-
@amplifier 否是问题的答案 - 正如 Cameron 指出的那样,CMD 不会在您的代码中停止(而且看起来正是您想要实现某种远程 CMD / telnet) - 所以它永远不会有“输出结束”。此外,没有任何类型的“命令执行结束”标记,因此您真的看不到“ping”或任何其他命令是否完成或等待用户输入或打开自己的子提示,如“ftp”。跨度>
标签: c# processstartinfo