2013-04-08 194 views
1

我想從我的c#應用程序在cmd上運行命令。如何從c#執行cmd命令#

我想:

string strCmdText = "ipconfig"; 
     System.Diagnostics.Process.Start("CMD.exe", strCmdText); 

結果:

cmd窗口彈出,但該命令沒有做什麼。

爲什麼?

+0

IPCONFIG僅僅是一個exe嘗試'的System.Diagnostics.Process。開始('ipconfig');' – EaterOfCode 2013-04-08 12:18:15

回答

6

使用

System.Diagnostics.Process.Start("CMD.exe", "/C ipconfig"); 

如果你想有CMD打開仍在使用:

System.Diagnostics.Process.Start("CMD.exe", "/K ipconfig"); 
+0

然後如何發送未來的命令? – 2017-10-04 11:54:29

4

codeproject

public void ExecuteCommandSync(object command) 
    { 
     try 
     { 
      // create the ProcessStartInfo using "cmd" as the program to be run, 
      // and "/c " as the parameters. 
      // Incidentally, /c tells cmd that we want it to execute the command that follows, 
      // and then exit. 
     System.Diagnostics.ProcessStartInfo procStartInfo = 
      new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command); 

     // The following commands are needed to redirect the standard output. 
     // This means that it will be redirected to the Process.StandardOutput StreamReader. 
     procStartInfo.RedirectStandardOutput = true; 
     procStartInfo.UseShellExecute = false; 
     // Do not create the black window. 
     procStartInfo.CreateNoWindow = true; 
     // Now we create a process, assign its ProcessStartInfo and start it 
     System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
     proc.StartInfo = procStartInfo; 
     proc.Start(); 
     // Get the output into a string 
     string result = proc.StandardOutput.ReadToEnd(); 
     // Display the command output. 
     Console.WriteLine(result); 
      } 
      catch (Exception objException) 
      { 
      // Log the exception 
      } 
    }