在 C 中,调用 CMD 命令行是一个常见的需求,无论是进行系统维护、自动化测试还是日常开发任务。C 提供了多种方法来实现这一功能。以下将详细介绍如何在 C 中调用 CMD 命令行,并实现系统命令的自...
在 C# 中,调用 CMD 命令行是一个常见的需求,无论是进行系统维护、自动化测试还是日常开发任务。C# 提供了多种方法来实现这一功能。以下将详细介绍如何在 C# 中调用 CMD 命令行,并实现系统命令的自动化。
System.Diagnostics.Process 类System.Diagnostics.Process 类是 C# 中用于启动和管理外部程序的标准类。以下是如何使用它来调用 CMD 命令行:
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 命令行,实现系统命令的自动化。这种方法灵活且功能强大,可以满足各种自动化需求。