在C#中执行批处理文件
在C#中,可以使用Process
类执行批处理文件。但是,如果批处理文件位于C:\Windows\System32
目录中,则执行可能会失败并返回ExitCode 1,指示发生一般错误。
为了解决这个问题,请在ExecuteCommand()
函数中重定向标准输出和错误流:
<code class="language-csharp">public void ExecuteCommand(string command) { int exitCode; ProcessStartInfo processInfo; Process process; processInfo = new ProcessStartInfo("cmd.exe", "/c " + command); processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; processInfo.RedirectStandardError = true; processInfo.RedirectStandardOutput = true; process = Process.Start(processInfo); process.WaitForExit(); string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); exitCode = process.ExitCode; Console.WriteLine("输出>>" + (String.IsNullOrEmpty(output) ? "(无)" : output)); Console.WriteLine("错误>>" + (String.IsNullOrEmpty(error) ? "(无)" : error)); Console.WriteLine("ExitCode: " + exitCode.ToString()); process.Close(); }</code>
修改1:
如果错误仍然存在,请将批处理文件移动到System32
目录之外的其他位置。
修改2:
为了避免在读取流时出现潜在的死锁,请实现如下所示的异步读取方法:
<code class="language-csharp">public void ExecuteCommand(string command) { int exitCode; ProcessStartInfo processInfo; Process process; processInfo = new ProcessStartInfo("cmd.exe", "/c " + command); processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; processInfo.RedirectStandardError = true; processInfo.RedirectStandardOutput = true; process = Process.Start(processInfo); process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine("输出>>" + e.Data); process.BeginOutputReadLine(); process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine("错误>>" + e.Data); process.BeginErrorReadLine(); process.WaitForExit(); exitCode = process.ExitCode; Console.WriteLine("ExitCode: {0}", exitCode); process.Close(); }</code>
以上是如何在C#中正确执行批处理文件并处理ExitCode 1错误?的详细内容。更多信息请关注PHP中文网其他相关文章!