Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a .bat file from a C# windows form app?

What I need to do is have a C# 2005 GUI app call a .bat and several VBScript files at user's request. This is just a stop-gap solution until the end of the holidays and I can write it all in C#. I can get the VBScript files to execute with no problem but I am unable to execute the .bat file. When I "click" in the C# app to execute the .bat file a DOS window opens up and closes very fast and the test .bat file does not execute - "Windows does not recognize bat as an internal or external command" is the error returned in the DOS box. If I simply doubl-click the .bat file or manually run it from the command prompt it does execute. I also need the .bat file to execute silently unless a user interaction is required - this script copies 11k+ files to folders on a networked machine and occasionally Windows "forgets" if the destination is a file or directory and asks for the user to tell it what it is (this is a whole other issue not for discussion here...needless to say I am annoyed by it).

So far in my C# source I have this :

Process scriptProc = new Process();


        if (File.Exists("c:\\scripts\\batchfile1.bat"))
        {

            scriptProc.StartInfo.FileName = @"cscript";
            scriptProc.StartInfo.Arguments = ("cmd.exe", "/C C:\\scripts\\batchfile1.bat"); // Wacky psuedo code //
            scriptProc.Start();
            scriptProc.WaitForExit(1500000);
            scriptProc.Close();

        }

        if (!File.Exists("c:\\scripts\\batchfile1.bat"))
        {
        }

I am aware that this code does not work - but it is essentially what I want it to do. What I am looking at is something like this for .bat files. I assume I have to tell the system to use cmd to run the .bat. I am at a loss as to how to do this. I have checked out this site which is for C# 2003. Not much help for me as I am very green with C#.

EDIT: Using Kevin's post I attempted it again. Same solution script from that post but modified for me since I do not need to redirect:

 System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.FileName = "C:\\scripts\\batchfile1.bat";
            proc.StartInfo.RedirectStandardError = false;
            proc.StartInfo.RedirectStandardOutput = false;
            proc.StartInfo.UseShellExecute = false;
            proc.Start();
            proc.WaitForExit();
like image 804
wergeld Avatar asked Dec 26 '08 17:12

wergeld


1 Answers

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

like image 95
kemiller2002 Avatar answered Sep 22 '22 16:09

kemiller2002