简体   繁体   中英

Execute a batch file from c# and store result into a variable

I am writing a program that is running a batch file, and will need the output further in the program. this is my C# code:

public void ExecuteBatFile()
    {
        Process proc = null;
        try
        {

            string targetDir = string.Format("C:\\Users");   //this is where mybatch.bat lies
            proc = new Process();
            proc.StartInfo.WorkingDirectory = targetDir;
            proc.StartInfo.FileName = "batch.bat";
            proc.StartInfo.Arguments = string.Format("10");  //this is argument
            proc.StartInfo.CreateNoWindow = false;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;  //this is for hiding the cmd window...so execution will happen in back ground.
            proc.Start();
            string output = proc.StandardOutput.ReadToEnd();
            Console.WriteLine(output);

            proc.WaitForExit();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
        }
    }
}

Once I run I get this error though:

Exception thrown: 'System.InvalidOperationException' in System.dll Exception Occurred :StandardOut has not been redirected or the process hasn't started yet., at System.Diagnostics.Process.get_StandardOutput() at CefSharp.MinimalExample.Wpf.CallBatchFile.ExecuteBatFile() in C:\\Users\\CefSharp.MinimalExamplemaster\\CefSharp.MinimalExample.Wpf\\CallBatchFile.cs:line 27

The batch file runs successfully, but then I'm not able to store the result into a variable. I can't get it to work in anyway. Has anyone got any suggestion? This is my moch batch:

@echo off
cd C:\users\934874
echo.>silvio.txt
title This is your first batch script!
echo Welcome to batch scripting!
if "%errorlevel%"=="0" cls &Echo Success.
if "%errorlevel%"=="1" cls &Echo Fail
pause

The output that I'm expecting is either Success / Fail at console, and store that as a string into a variable. Thanks in advance for your help

Need to redirect the output

proc.StartInfo.RedirectStandardOutput = true;

https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput(v=vs.110).aspx

Quoting from https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.useshellexecute(v=vs.110).aspx

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 can be either a fully qualified path to the executable, or a simple executable name that the system will attempt to find within folders specified by the PATH environment variable.

One of the simplest way is to make your batch file write its output to a text file. Then your main program can read the text file after the batch has finished.

If you really want to read from the standard output stream, please take a look at this other SO post: Capturing console output from a .NET application (C#)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM