Why
- 最近在做一个有关于
C#
的项目,有一部分就是需要调用cmd
的批处理,正好不管是bat
还是python
都可以使用调用cmd
来实现功能,所以记录一下。
How
private void BatExecuteTask(string scrpitPath, out string output, out string error)
{
using var process = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = $@"{Environment.CurrentDirectory}\{scrpitPath}",
Arguments = scrpitPath,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardError = true,
WorkingDirectory = $@"{Environment.CurrentDirectory}",
Verb = "runas"
},
};
process.Start();
string outputData = string.Empty;
string errorData = string.Empty;
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.OutputDataReceived += (sender, e) =>
{
outputData += (e.Data + Environment.NewLine);
};
process.ErrorDataReceived += (sender, e) =>
{
errorData += (e.Data + Environment.NewLine);
};
process.WaitForExit();
process.Close();
output = outputData;
error = errorData;
if (!string.IsNullOrWhiteSpace(output))
{
this.Result = output;
return;
}
if (!string.IsNullOrWhiteSpace(error))
{
this.Result = error;
return;
}
}
Tips
- 注意在读取输出的时候一定要用异步流,反正我不使用的话有些脚本一直卡死。