Here’s a piece of code, which enables running a batch file from C# code. I found this on google, but don’t remember the link for it. So, if somebody have copyright for this code, please let me know. I’ll remove this from my site.

string basePath = htmpPath + “\\” + bookId.ToString() + “\\”;

// Get the full file path
string strFilePath = “C:\\Inetpub\\wwwroot\\test\\pdftohtml.bat”;

// Create the ProcessInfo object
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(strFilePath);
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
psi.WorkingDirectory = “C:\\Inetpub\\wwwroot\\test”;
psi.Arguments = basePath + ” ” + txt.Text + fileUploadControl.FileName + ” ” + txt.Text; ;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

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

// Open the batch file for reading
System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);

// 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());
}

strm.Close();

// Exit CMD.EXE
string stEchoFmt = “# {0} run successfully. Exiting”;

sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
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();


Leave a Reply

Your email address will not be published. Required fields are marked *