4

this code works fine on my test-system (Copy of the original Windows-Server 2008 R2)

private string _getNetFiles()
{
    // prepare execution process
    ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/c openfiles /query /Fo list");
    processStartInfo.CreateNoWindow = true;
    processStartInfo.UseShellExecute = false;
    processStartInfo.RedirectStandardError = true;
    processStartInfo.StandardOutputEncoding = System.Text.Encoding.GetEncoding(437);
    processStartInfo.RedirectStandardOutput = true;

    // execute
    Process process = Process.Start(processStartInfo);
    process.WaitForExit();


    // read outputs
    string stdOutput = process.StandardOutput.ReadToEnd();
    string stdError = process.StandardError.ReadToEnd();

    return stdOutput;
}

On the original system: I see the "cmd.exe /c openfiles /query /Fo list" task in the Task-Manger, but this task never end (process.WaitForExit() process never end ). Cmd on the original system: openfiles /query /fo list works also fine!

Where can the problem be?

regards raiserle

edit: I can stop the process with task-manager. The stdOutput is correct. Why don't end the cmd-taks.

raiserle
  • 677
  • 8
  • 31

1 Answers1

5

The child process is either waiting for input or for its output to be read. The pipe buffers are not infinitely big. You need to constantly drain both standard output as well as standard error.

Get Values from Process StandardOutput looks reasonable. https://stackoverflow.com/a/24084220/122718 documents how to safely read both streams.

Also note Visual Basic Capture output of cmd as well as everything that Hans Passant says on this topic.

Using the Process class without output redirection is quite tricky and poorly documented.

Community
  • 1
  • 1
usr
  • 168,620
  • 35
  • 240
  • 369
  • Any suggestions, why works this on the test-system? The error (reading the stderr to end) isn't on the test-system. The task is not blocking. – raiserle Oct 01 '14 at 17:57
  • I have no specific knowledge about what this command does and under what circumstances it might as for input. – usr Oct 02 '14 at 10:15