1

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

the _file_creator.bat file is in the same directory as the executed .bat file
That doesn't matter. The working directory is inherited from your C# program as the quote above shows. You have to set the working directory for the new process yourself for it to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.