2016-07-19 25 views
0

Ich versuche, den Standard aus cmd.exe (testen "DIR" -Befehl), und legen Sie es in ein Textfeld. Jedoch, wenn ich den Prozess starte, hängt das Programm (keine Taste gedrückt).Aufruf von cmd.exe mit Prozess in C# hängen

private void cmd_test() 
{ 
    Process pr = new Process() 
    { 
     StartInfo = { 
      FileName = "cmd.exe", 
      UseShellExecute = true, 
      CreateNoWindow = true, 
      RedirectStandardOutput = true, 
      RedirectStandardInput = true, 
      RedirectStandardError = true, 
     } 
    }; 

    pr.Start(); 
    pr.StandardInput.WriteLine("DIR"); 
    TextBox1.Text = pr.StandardOutput.ReadToEnd(); 
} 

Ich habe auch versucht Arguments = "DIR" in dem Startinfo-Block statt Console.WriteLine.

Wie sende ich ordnungsgemäß einen Befehl an cmd.exe, ohne dass es hängt?

Antwort

1

Hier gehen Sie:

using (var p = new Process()) 
    { 
    p.StartInfo.CreateNoWindow = true; 
    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
    p.StartInfo.UseShellExecute = false; 
    p.StartInfo.RedirectStandardOutput = true; 
    p.StartInfo.FileName = "cmd.exe"; 
    p.StartInfo.Arguments = "/C dir"; 
    p.Start(); 
    var output = p.StandardOutput.ReadToEnd(); 
    p.WaitForExit(); 
    richTextBox1.Text = output; 
    } 
+0

Arbeitete, danke! Weißt du, warum es an meiner Version lag? – FyreeW

+0

Sie müssen "/ C dir" –

+0

auch 'UseShellExecute' muss auf false gesetzt werden, um Ausgabeströme umzuleiten. Weitere Informationen finden Sie hier https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.useshellexecute(v=vs.110).aspx – Fred