代码如下:新建进程,运行cmd,参数为bat文件的内容。
注意如果是IIS部署,且批处理中需要管理员权限,则还需要将该网站的应用程序池–高级设置–标识设置为:LocalSystem
string filePath = Server.MapPath("/bat.bat");
if (File.Exists(filePath))
{
Process process = new Process();
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe", //这里执行的是bat文件,所以要在cmd中执行
// Use /K to have the new cmd window stay after the batch file is done
Arguments = $"/C \"{filePath}\"",
Verb = "runas", //管理员身份运行
RedirectStandardOutput = true, //重定向输出为了前台展示cmd内容
RedirectStandardError = true,
UseShellExecute = false
};
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
//获取输出结果
string output = process.StandardOutput.ReadToEnd();
this.txtResult.Text = "已执行。\n" + output;
}