C++可以通过system()执行系统命令,那么C#如何执行系统命令呢?
步骤
C#并没有直接提供执行系统命令的函数,但是我们可以通过静默启动cmd实现。
注意
请先引用命名空间
C#
using System.Diagnostics;
初始化cmd进程对象
C#
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = System.Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\cmd.exe";
startInfo.Arguments = "/C " + "执行的命令";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
process.StartInfo = startInfo;
打开cmd,读取输入,并退出
C#
try
{
process.Start();
process.WaitForExit();
string outstr = process.StandardOutput.ReadToEnd();
}
finally
{
process.Close();
}
实例
读取输入的命令,执行后输出结果
C#
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace CMD
{
class Program
{
static string[] c = { "1", "1" };
static Process process = new Process();
static void Main(string[] args)
{
if (args != c)
{
Console.Beep(4000, 500);
Console.Title = "CMD模拟";
Console.WriteLine("[ 控制台模拟 Ver=1.0 Author=C#之家 Website=https://www.chsarphome.xyz ]");
}
Console.Write("->");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = System.Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\cmd.exe";
startInfo.Arguments = "/C " + Console.ReadLine();
if (startInfo.Arguments == "/C exit")
{
Environment.Exit(0);
}
if (startInfo.Arguments == "/C cls")
{
Console.Clear();
Main(c);
}
if (startInfo.Arguments == "/C ver")
{
Console.WriteLine("[ 控制台模拟 Ver=1.0 Author=吕舒君 Website=https://cszj.wang ]");
Main(c);
}
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
process.StartInfo = startInfo;
try
{
process.Start();
process.WaitForExit();
string outstr = process.StandardOutput.ReadToEnd();
Console.WriteLine(outstr);
}
finally
{
process.Close();
}
Main(c);
}
}
}