C#中执行CMD命令的完整实现与错误处理方案
在C#开发中,经常需要调用系统命令行工具执行操作。本文通过完整示例演示如何正确执行CMD命令并处理输出结果。
核心实现原理
C#通过System.Diagnostics.Process类实现命令行调用,关键配置参数如下:
| 参数 | 作用 | 示例值 |
|---|---|---|
| FileName | 执行程序 | cmd.exe |
| Arguments | 命令参数 | /c dir |
| RedirectStandardOutput | 重定向输出 | true |
| UseShellExecute | 是否使用shell | false |
| CreateNoWindow | 是否创建窗口 | true |
完整代码实现
C#:
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入要执行的CMD命令:");
string command = Console.ReadLine();
// 创建进程启动信息
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/c {command}", // /c参数表示执行后关闭CMD窗口
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
// 创建并启动进程
using (Process process = new Process { StartInfo = psi })
{
process.Start();
// 异步读取输出和错误流
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
// 显示结果
if (!string.IsNullOrEmpty(output))
Console.WriteLine($"输出:\n{output}");
if (!string.IsNullOrEmpty(error))
Console.WriteLine($"错误:\n{error}");
}
Console.WriteLine("\n按任意键退出...");
Console.ReadKey();
}
}
XML:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
关键技术点
- 参数配置:必须设置UseShellExecute=false才能重定向输出流
- 错误处理:通过RedirectStandardError捕获命令执行错误
- 资源释放:使用using语句确保进程资源正确释放
- 异步读取:采用ReadToEnd()同步读取方式,简单场景下足够使用
使用场景示例
| 场景 | 命令示例 |
|---|---|
| 文件操作 | dir /s |
| 网络诊断 | ipconfig /all |
| 系统管理 |
sfc /scannow |
本站大部分文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了您的权益请来信告知我们删除。邮箱:1451803763@qq.com