2013-01-31 2 views
0

다음 코드가 있습니다.cmd.exe 프로세스가 완료되지 않음

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"; 

실행은 "문자열 consoleOutput을"에 도달하지만 결코 코드가 StandardOutput을 읽고 걸리면 즉 "문자열 DIR을"에 도달하지 않습니다. 이것이 차이가 나는 경우 콘솔 응용 프로그램 내에서 실행됩니다.

+2

콘솔 응용 프로그램에서 이미 실행중인 경우'cmdconfig '를 불필요하게 생성하는 대신 자체적으로'ipconfig'를 호출하지 않는 이유는 무엇입니까? – Petesh

+0

console.write로이 작업을 수행 할 수 있습니까? – coolblue2000

+0

console.write는 실제로 프로세스를 시작하지 않으며, 프로세스를 시작하는 것은 'Process.Start (si)'입니다. – Petesh

답변

1

스트림을 닫아 명시 적으로 표준 입력에 대한 쓰기를 완료해야합니다. Microsoft's example을 참조하십시오. 요약

:

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

편집 : Visual Studio에서 테스트.

그런데Write() 대신 WriteLine()을 사용하고 싶습니다.

+0

완벽하게 작동합니다. 감사합니다. – coolblue2000

0

Write 대신 WriteLine을 사용하면 마지막 개행이있는 문자열을 쓸 수 있습니다. (Flush()에도 전화해야하지만 잘 모르겠습니다). 또 다른 대답에 따르면, 스트림을 Close에게 아프지 않을 것입니다.

그리고 예, cmd.exe이 필요하지 않은 경우 ipconfig을 직접 (의견에서 @Petesh로 알리는 것으로) 시작할 수 있습니다.

+0

'Flush()'와'FlushAsync()'는 어떤 이유로 든하지 않습니다. 이유를 모르겠다. – Jason

관련 문제