June 29, 2010

Run Batch File in C#

Quick method to create and run a batch file, the contents of which are passed as a string.
private void RunBatchFile(
  string batFileContents, 
  int waitToFinishSecs)
{
    string batFile = Path.GetTempFileName();
    batFile = batFile.Replace(".tmp", ".bat");
    File.WriteAllText(batFile, batFileContents);
    string dir = System.IO.Path.GetDirectoryName(batFile);
    string file = System.IO.Path.GetFileName(batFile);

    Process process = new Process();
    process.StartInfo.FileName = file;
    process.StartInfo.WorkingDirectory = dir;
    bool res = false; // Dont do anything with this yet
    try
    {
        process.Start();
        res = process.WaitForExit(waitToFinishSecs*1000);
        File.Delete(batFile);
    }
    catch (Win32Exception winex)
    {
        Debug.WriteLine(winex.ToString());
        throw;
    }    
}

No comments: