阅读量:2
在C#中,你可以使用System.Diagnostics命名空间中的Process类来执行CMD命令并获取返回结果
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
// 要执行的CMD命令,例如:dir
string command = "dir";
// 创建一个ProcessStartInfo对象,用于存储命令的属性
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd";
startInfo.Arguments = "/c " + command; // /c 用于执行后面的命令
startInfo.RedirectStandardOutput = true; // 将输出重定向到Process.StandardOutput
startInfo.UseShellExecute = false; // 不使用系统外壳程序启动命令
startInfo.CreateNoWindow = true; // 不创建新的窗口
// 创建一个新的Process对象,并使用StartInfo属性
using (Process process = Process.Start(startInfo))
{
// 读取命令的输出
using (StreamReader reader = process.StandardOutput)
{
string output = reader.ReadToEnd(); // 读取所有输出
Console.WriteLine(output); // 将输出打印到控制台
}
}
}
}
这个示例将执行dir命令(在Windows系统中列出当前目录的文件和文件夹),并将结果打印到控制台。你可以根据需要修改command变量来执行其他CMD命令。
以上就是关于“c#如何执行cmd命令并返回结果”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm