首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[教程]C# 调用CMD命令行,轻松实现系统命令自动化

发布于 2025-06-22 10:11:58
0
290

在 C 中,调用 CMD 命令行是一个常见的需求,无论是进行系统维护、自动化测试还是日常开发任务。C 提供了多种方法来实现这一功能。以下将详细介绍如何在 C 中调用 CMD 命令行,并实现系统命令的自...

在 C# 中,调用 CMD 命令行是一个常见的需求,无论是进行系统维护、自动化测试还是日常开发任务。C# 提供了多种方法来实现这一功能。以下将详细介绍如何在 C# 中调用 CMD 命令行,并实现系统命令的自动化。

使用 System.Diagnostics.Process

System.Diagnostics.Process 类是 C# 中用于启动和管理外部程序的标准类。以下是如何使用它来调用 CMD 命令行:

创建 Process 对象

using System.Diagnostics;
Process process = new Process();

设置启动信息

process.StartInfo.FileName = "cmd.exe"; // 指定要启动的程序
process.StartInfo.UseShellExecute = false; // 不使用操作系统外壳程序启动
process.StartInfo.RedirectStandardInput = true; // 重定向标准输入
process.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
process.StartInfo.RedirectStandardError = true; // 重定向标准错误
process.StartInfo.CreateNoWindow = true; // 不创建新窗口

启动进程

process.Start();

发送命令

StreamWriter stdin = process.StandardInput;
StreamReader stdout = process.StandardOutput;
StreamReader stderr = process.StandardError;
stdin.WriteLine("your command here"); // 发送命令
stdin.Flush();

读取输出

string output = stdout.ReadToEnd();
string error = stderr.ReadToEnd();
Console.WriteLine("Output:");
Console.WriteLine(output);
Console.WriteLine("Error:");
Console.WriteLine(error);

关闭进程

process.WaitForExit();
process.Close();

示例代码

以下是一个完整的示例,演示如何使用 Process 类调用 CMD 命令行:

using System;
using System.Diagnostics;
class Program
{ static void Main() { Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.Start(); StreamWriter stdin = process.StandardInput; StreamReader stdout = process.StandardOutput; StreamReader stderr = process.StandardError; stdin.WriteLine("dir"); stdin.Flush(); string output = stdout.ReadToEnd(); string error = stderr.ReadToEnd(); Console.WriteLine("Output:"); Console.WriteLine(output); Console.WriteLine("Error:"); Console.WriteLine(error); process.WaitForExit(); process.Close(); }
}

总结

通过使用 System.Diagnostics.Process 类,你可以轻松地在 C# 中调用 CMD 命令行,实现系统命令的自动化。这种方法灵活且功能强大,可以满足各种自动化需求。

评论
一个月内的热帖推荐
csdn大佬
Lv.1普通用户

452398

帖子

22

小组

841

积分

赞助商广告
站长交流