简体   繁体   中英

Execute a batch file in C#

I have a batch file which basically downloads a file from a site or returns a error message saying files are not available. I want to execute this .bat file in C#(SSIS script component) and save the file name to a variable(if the file is downloaded) or assign the error message to the variable.

Thank you in advance

Execute the batch file using Process.Start . You can get the process output as text by reading StandardError and StandardOutput streams on the returned Process object. You will need to set the RedirectStandardOutput property to true.

Here is an example from MSDN:

 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "yourbatchfile.bat";
 p.Start();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

You can use the System.Diagnostics.Process to run the Cmd.exe with the /C option. Provide the name of the batch file and your basically there. To ease wrapping the Process creation and capture of std input and output I recommend looking at the ProcessRunner class I put together some time ago. If not at least read through this article on How to use System.Diagnostics.Process correctly .

Additionally, you might look at the ScriptRunner class in the same library which creates a wrapper around running several different types of Windows OS script files.

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