Get Values from Process StandardOutput

后端 未结 1 1564
生来不讨喜
生来不讨喜 2020-11-29 13:01

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 String         


        
相关标签:
1条回答
  • 2020-11-29 13:23

    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.

    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);
    
    0 讨论(0)
提交回复
热议问题