Execute batch file in C#
In C#, you can use the Process
class to execute batch files. However, if the batch file is located in the C:\Windows\System32
directory, execution may fail and return ExitCode 1, indicating a general error.
To resolve this issue, redirect the standard output and error streams in the ExecuteCommand()
function:
<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>
Modification 1:
If the error persists, move the batch file to a different location outside of the System32
directory.
Modification 2:
To avoid potential deadlocks when reading the stream, implement an asynchronous read method like this:
<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>
The above is the detailed content of How to Properly Execute Batch Files in C# and Handle ExitCode 1 Errors?. For more information, please follow other related articles on the PHP Chinese website!