Process使用

时间:2023-03-10 02:37:28
Process使用

最近在一个项目中,需要在C#中调用cmd窗口来执行一个命令,使用到了Process这个类,使用过程中遇到不少问题,好在终于解决了。赶紧记录下来。

Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.WorkingDirectory = "C:\\Program Files\\GPAC";//因为我要调用的是第三方程序的一个exe命令,所以,必须要把路径设为exe所在的目录
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.Verb = "runas";//这一句话要带上,确保以管理员权限执行命令,及时程序是以Administrator账号运行的,这句话也要带上
if (process.Start())
{
process.StandardInput.WriteLine(cmdstr);//cmdstr就是要执行的命令语句
process.StandardInput.WriteLine("exit");
}
//process.WaitForExit();//以这种方式使用Process的时候,这句话可以不要
string error = process.StandardError.ReadToEnd();//输出错误信息
string test = process.StandardOutput.ReadToEnd();//输出程序执行完之后的输出信息