Run a .BAT file from .Net with parameters
Posted by Em on 7 February, 2008
9 Comments
This item was filled under [ .Net ]
Last week, I had to execute a batch file using ASP.Net with parameters. I searched couple of forums, tried few codes but one of them worked really nice. I have tweaked the code to use parameters and its working! =)
public string executeBAT(string workingDir, string batchFile, string batchParameters)
{
//workingDir e.g. "c:\\temp\\" (where your batch file is placed)
//batchFile e.g. "mybatchfile" (or mybatchfile.bat)
//batchParameters e.g. "p1 p2 p3"
string processedResult = "";
// Create the ProcessInfo object
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
psi.WorkingDirectory = workingDir;
// Start the process
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
// Attach the output for reading
System.IO.StreamReader sOut = proc.StandardOutput;
// Attach the in for writing
System.IO.StreamWriter sIn = proc.StandardInput;
sIn.WriteLine(batchFile + " " + batchParameters);
// Exit CMD.EXE
sIn.WriteLine("EXIT");
// Close the process
proc.Close();
// Read the sOut to a string.
string results = sOut.ReadToEnd().Trim();
results = results.Replace(System.Environment.NewLine, "<br>");
// Close the io Streams;
sIn.Close();
sOut.Close();
return processedResult;
}
Popularity: 536 views
9 Comments on “Run a .BAT file from .Net with parameters”
mushuu bahi i just started VB
is it enough to try hands on ASP.net
i heard its pretty much same
wat say?
ASP.Net is only a technology. The coding part is done in either VB or C#. In case you are doing VB.Net, you won’t find much trouble shifting to ASP.Net anytime =)
ok thanks
Nice blog. Love the white on black! FYI: If you need a great web host, try Server Intellect. They really know what they are doing and have upgraed to the new 2008 Microsoft Server.
This code worked great on my local machine, but isn’t working on the server. Any ideas why?
Are you getting any error? Did you update the workingDir?
Or you could just:
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(”cmd.exe”);
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
psi.WorkingDirectory = System.IO.Path.GetDirectoryName(bat);
psi.Arguments = “/C \”" + bat + “\”";
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);