问题
I have a .bat file to be executed.
Inside that .bat file, at its end is that code
START _file_creator.bat %some_arg_name%
ENDLOCAL
EXIT
I don't want to show the window during the execution and also I must wait until the operation doing by this .bat file is completed and then terminate the execution (at the end of the operation I see the standard text "Press any key to continue"). I need also to check the output and errors by that file, so I'm trying to use that code:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = @"C:\m_f\_config.bat";
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();
output1 = proc.StandardError.ReadToEnd();
proc.WaitForExit();
output2 = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
But all I get is the error
Windows can not find file "_file_creator.bat".
Make sure you typed the name correctly and try again.
of course if I run that .bat file with the proc.StartInfo.UseShellExecute = true it works fine, but in that case I can't set RedirectStandardError = true and RedirectStandardOutput = true
How to fix it ?
Edit
using that code it works now
proc.StartInfo.FileName = @"C:\m_f\_config.bat";
proc.StartInfo.WorkingDirectory = @"C:\m_f\";
回答1:
Try setting the working directory correctly or make sure that _file_creator.bat is somewhere in the PATH. See the documentation about the working directory in conjunction with UseShellExecute:
The WorkingDirectory property behaves differently depending on the value of the UseShellExecute property. When UseShellExecute is true, the WorkingDirectory property specifies the location of the executable. If WorkingDirectory is an empty string, it is assumed that the current directory contains the executable.
When UseShellExecute is false, the WorkingDirectory property is not used to find the executable. Instead, it is used only by the process that is started and has meaning only within the context of the new process. When UseShellExecute is false, the FileName property must be a fully qualified path to the executable.
来源:https://stackoverflow.com/questions/11177554/c-sharp-bat-file-execution-with-error-output-redirection