简体   繁体   中英

Executing batch file from c# silently

I know this question has been asked previously and I have tried all the solutions given in those posts before but I can't seem to make it work:-

static void CallBatch(string path)
        {
            int ExitCode;
            Process myProcess;

            ProcessStartInfo ProcessInfo;
            ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + path);
            ProcessInfo.CreateNoWindow = true;
            ProcessInfo.UseShellExecute = true;

            myProcess = Process.Start(ProcessInfo);
            myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            myProcess.WaitForExit();

            myProcess.EnableRaisingEvents = true;
            myProcess.Exited += new EventHandler(process_Exited);

            ExitCode = myProcess.ExitCode;

            Console.WriteLine("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
            myProcess.Close();
        }

When I try to call the batch file, it still shows the window even though createNoWindow and UseShellExecute are both set to true.

Should I put something else to make it run the batch file silently?

Try this:

Process myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.Arguments = "/c " + path;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(process_Exited);
myProcess.Start();
myProcess.WaitForExit();
ExitCode = myProcess.ExitCode;

The idea is to not manipulate myProcess.StartInfo after you have started your process: it is useless. Also you do not need to set UseShellExecute to true , because you are starting the shell yourself by calling cmd.exe .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM