Running Command Line Bat Files From a Web Page ASP.NET C#
We needed the ability to run some batch processes without having to remote to the server. I put together a small ASP.NET app that allowed us to do this. Found some code for running standard command line application through .NET and modified/extended it to work through a web interface.
Here is the code that does the bulk of the of the work for running the bat files.
public static string ProcessBatFile(string batFile)
{
string val = "";
if (!File.Exists(batFile))
{
throw new Exception(batFile + " does not exists");
}
// 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;
// Start the process
System.Diagnostics.Process proc =
System.Diagnostics.Process.Start(psi);
// Open the batch file for reading
System.IO.StreamReader strm = proc.StandardError;
// Attach the output for reading
System.IO.StreamReader sOut = proc.StandardOutput;
// Attach the in for writing
System.IO.StreamWriter sIn = proc.StandardInput;
// Write each line of the batch file to standard input
/*while(strm.Peek() != -1)
{
sIn.WriteLine(strm.ReadLine());
}*/
sIn.WriteLine(batFile);
strm.Close();
// Exit CMD.EXE
string stEchoFmt = "# {0} run successfully. Exiting";
sIn.WriteLine(String.Format(stEchoFmt, batFile));
sIn.WriteLine("EXIT");
// Close the process
proc.Close();
// Read the sOut to a string.
string results = sOut.ReadToEnd().Trim();
// Close the io Streams;
sIn.Close();
sOut.Close();
val = results;
return val;
}
I created CMD prompt in CSS to make it look legit. It just displays the captured output from the method above.

This can be extremely unsafe for a server. Your sys admin should question setting something like this up. Please let them know there are steps that can be taken to help make this a safe process such as requiring authentication to access this script and only allow the bat files to run from set directory.