简体   繁体   中英

Problem invoking external .exe using c#

I'm trying to run this .exe file from my c# code, it does call the .exe file but then it crashes midway through. If I click on the .exe on the explorer it does its job, so I wonder if there's a problem with the code I'm using to invoke it:

            string fileName =  "loadscript.exe";
            Utils.Logger.Info("Calling script:" + fileName);
            Process process = new Process();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.FileName = fileName;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();
            Thread.Sleep(10000);
            process.WaitForExit();
            int exitCode = process.ExitCode;
            string output = process.StandardOutput.ReadToEnd();
            Utils.Logger.Info(".exe Output: ");
            Utils.Logger.Info(output);
  Thread.Sleep(10000);
  process.WaitForExit();
  int exitCode = process.ExitCode;
  string output = process.StandardOutput.ReadToEnd();

It seems to me like this is creating a deadlock and this might be the problem for the eventual crash. Remove the sleep and try this instead:

  string output = process.StandardOutput.ReadToEnd();
  process.WaitForExit();
  int exitCode = process.ExitCode;

Please see the answer to this question for an explanation:

ResGen.exe stucks when redirect output

       process.StartInfo.UseShellExecute = false;

That requires you to specify the name of a .exe file. With it set to true, another Windows function is used to start the file, it is smart enough to figure out that a .bat file requires cmd.exe to be started to interpret the commands in the .bat file.

Which is what you need to do yourself now, the FileName must be "cmd.exe", the Arguments property needs to be "loadscript.bat".

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