简体   繁体   中英

cmd.exe process never completes

I have the following code.

ProcessStartInfo si = new ProcessStartInfo("cmd.exe");
si.RedirectStandardInput = true;
si.RedirectStandardOutput = true;
si.UseShellExecute = false;
si.WindowStyle = ProcessWindowStyle.Hidden;
si.CreateNoWindow = true;
Process p = Process.Start(si);
p.StandardInput.Write("ipconfig");
p.StandardInput.Write("exit");
string consoleOutput = p.StandardOutput.ReadToEnd();
string dir="here";

The execution reaches "string consoleOutput" but never reaches "string dir" ie the code gets stuck on reading the StandardOutput. It is runnung from within a console application if this makes any difference.

You have to explicitly finish writing to the standard input by closing the stream. See Microsoft's example .

In summary:

        p.StandardInput.Write("exit");
        p.StandardInput.Close(); // <-- You need this
        string consoleOutput = p.StandardOutput.ReadToEnd();

Edit: Tested in Visual Studio.

By the way , you want to use WriteLine() instead of Write() .

Use WriteLine instead of Write to write a string with a final newline. (You might have to call Flush() as well, but I'm not sure). It won't hurt to Close the stream, as another answer says.

And yes, you don't need cmd.exe , you can start ipconfig directly (as advised by @Petesh in a comment).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM