2012-06-14 5 views
0

Je veux appeler la commande d'invite de commande en utilisant Process.Start, puis en utilisant StandardOutput je veux lire en utilisant StreamReader dans mon application, mais quand je lance le programme ci-dessous, dans le MessageBox je trouve juste le chemin jusqu'à Débogage, ma commande que j'ai énoncée dans les arguments n'exexude pas.Passer des arguments à la classe ProcessStartInfo

ProcessStartInfo info = new ProcessStartInfo("cmd.exe", "net view"); 
      info.UseShellExecute = false; 
      info.CreateNoWindow = true; 
      info.RedirectStandardOutput = true;  

      Process proc = new Process(); 
      proc.StartInfo = info; 
      proc.Start(); 

      using(StreamReader reader = proc.StandardOutput) 
      { 
       MessageBox.Show(reader.ReadToEnd()); 
      } 

ici ma commande net view ne s'exécute jamais.

Répondre

4

Si vous souhaitez exécuter une commande avec cmd vous devez spécifier l'argument /c aussi:

new ProcessStartInfo("cmd.exe", "/c net view"); 

Dans ce cas, vous n'avez pas besoin cependant cmd du tout. net est un programme natif et peut être exécuté tel quel, sans coquille:

new ProcessStartInfo("net", "view"); 
+0

grâce @Joey: Cela m'a beaucoup aidé – Abbas

+1

Si cela répond à votre question, pourquoi ne pas cliquer sur la coche? – Almo

1

Rappelez-vous aussi d'intercepter le StandardErrorOutput ou ne verra rien:

var startInfo = new ProcessStartInfo("net", "view"); 
startInfo.UseShellExecute = false; 
startInfo.CreateNoWindow = true; 
startInfo.RedirectStandardError = true; 
startInfo.RedirectStandardOutput = true; 

using (var process = Process.Start(startInfo)) 
{ 
    string message; 

    using (var reader = process.StandardOutput) 
    { 
     message = reader.ReadToEnd(); 
    } 

    if (!string.IsNullOrEmpty(message)) 
    { 
     MessageBox.Show(message); 
    } 
    else 
    { 
     using (var reader = process.StandardError) 
     { 
      MessageBox.Show(reader.ReadToEnd()); 
     } 
    } 
} 
Questions connexes