I receive console output in my application. I use code from here (the accepted solution). But I never get null in my OutputDataReceived. Instead, I have String.Empty at the end of the output. Would it be correct to use String.NullOrEmpty instead of just comparing to 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));
}
}
}
}
Update: It seems that it won't work multiline output. The question is why there's no null in a.Data