How to run a batch file from C# in desktop application

To execute the batch file in c#, here is the code through which you can easily get the output from batch file.

// Get the full file path
string strFilePath = filePath;(full path for ex: c:\\batchfile\\somefile.bat)

// Create the ProcessInfo object

System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(strFilePath);
psi.CreateNoWindow = true;
psi.Arguments = args;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;

psi.WorkingDirectory = workingDirectory; (for ex: c:\\batchfile)

// Start the process
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);

// Get the result

string results = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();


// Close the process

Many thanks to Suresh Chaudhary for this post.


No comments:

Post a Comment