一、使用Process調用cmd命令
在c#中,使用Process可以方便地調用cmd命令並執行。
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c dir";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
Console.WriteLine(output);
上面的代碼演示了如何使用Process調用cmd並執行dir命令,最後將輸出打印到控制台中。
二、使用Process調用cmd腳本
除了執行單個命令,也可以使用Process執行cmd腳本。
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/k \"C:\\path\\to\\script.bat\"";
process.Start();
上面的代碼演示了如何使用Process調用名為script.bat的腳本文件。
三、使用PowerShell替代cmd
在一些情況下,PowerShell可以替代cmd進行更加強大的操作。下面演示如何使用Process調用PowerShell並執行。
Process process = new Process();
process.StartInfo.FileName = "powershell.exe";
process.StartInfo.Arguments = "-ExecutionPolicy ByPass -File C:\\path\\to\\script.ps1";
process.Start();
上面的代碼演示了如何使用Process調用名為script.ps1的PowerShell腳本文件。
四、使用cmd參數
有時候,我們需要用到一些cmd的參數來實現特定的功能。下面演示一些常用的參數。
- /c:執行指定的命令並退出。
- /k:執行指定的命令並繼續保持cmd窗口打開狀態。
- /s:在子目錄中執行指定的命令。
- /v:啟動時顯示所有版本信息。
代碼演示:
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c ipconfig";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
Console.WriteLine(output);
上面的代碼演示了如何使用/c參數執行ipconfig命令。
五、使用cmd重定向輸出
默認情況下,Process會將cmd輸出到控制台。如果需要獲取輸出結果,可以使用重定向功能。
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c dir";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
Console.WriteLine(output);
上面的代碼演示了如何將dir命令執行的結果存儲到output變量中,並打印到控制台。
六、使用cmd輸入命令
有時候,需要通過命令行輸入命令並執行。可以使用Process的StandardInput屬性來實現。
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
process.StandardInput.WriteLine("ipconfig");
process.StandardInput.Flush();
process.StandardInput.Close();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
Console.WriteLine(output);
上面的代碼演示了如何通過StandardInput屬性輸入ipconfig命令並執行,最後將輸出打印到控制台。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/233775.html