Get Values ​​from StandardOutput Process

I am trying to get output to show open documents on my machine, but it returns 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);

Edit:

In a further review, I see that I am getting an exception. During my diag run, I get the following: Proc.BasePriority is an exception of type System.InvalidOperationException

Edit:

Trying to print the code as:

string val = proc.StandardOutput.ReadToEnd();
MessageBox.Show(val);

The return value is also NULL, and Proc still had errors even after proc.start () ;.

+2
source share
1 answer

You should read both standard output and standard error streams. This is because you cannot read them as from a single stream.

, .

anycpu, openfiles 32- 64- . , .

, , ! > .

    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);
+10

All Articles