一、使用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/n/233775.html