C#开启cmd执行exe文件并输入指定参数
时间: 2024-10-23 19:02:18 浏览: 197
在C#中,你可以使用`System.Diagnostics.Process`类来启动一个新的进程并执行外部应用程序,如`.exe`文件,并传递参数。以下是一个基本示例,展示如何打开CMD、执行.exe文件以及传递参数:
```csharp
using System.Diagnostics;
public void RunExeWithParams(string exePath, string[] parameters)
{
// 创建新的ProcessStartInfo对象
ProcessStartInfo startInfo = new ProcessStartInfo();
// 设置要执行的程序路径
startInfo.FileName = exePath;
// 指定以管理员权限运行
startInfo.UseShellExecute = true;
startInfo.Verb = "runas"; // 使用runas以获取管理员权限
// 添加参数
startInfo.Arguments = string.Join(" ", parameters);
// 设定标准输出重定向为null,以便捕获输出流
startInfo.RedirectStandardOutput = false;
// 创建新的进程实例
using (Process process = new Process())
{
// 将上述信息设置给进程
process.StartInfo = startInfo;
// 启动进程
process.Start();
// 等待进程结束
process.WaitForExit();
}
}
// 调用函数,例如执行notepad.exe并传入参数
RunExeWithParams(@"C:\Windows\System32\notepad.exe", new string[] { "-s", "test.txt" });
```
在这个例子中,`-s test.txt`会被作为参数传递给`notepad.exe`。如果你想在命令行看到实际的执行结果,可以将`startInfo.RedirectStandardOutput = false;`改为`true`,然后处理`process.StandardOutput.ReadToEnd()`。
阅读全文
相关推荐


















