[英]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. 我正在尝试从我的C#代码运行此.exe文件,它确实调用了.exe文件,但随后中途崩溃了。 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: 如果我在资源管理器上单击.exe,它将完成其工作,所以我想知道我用来调用它的代码是否存在问题:
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: 请查看此问题的答案以获取解释:
process.StartInfo.UseShellExecute = false;
That requires you to specify the name of a .exe file. 这要求您指定.exe文件的名称。 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. 将其设置为true时,将使用另一个Windows函数来启动该文件,这一点足够聪明,可以弄清楚.bat文件需要启动cmd.exe来解释.bat文件中的命令。
Which is what you need to do yourself now, the FileName must be "cmd.exe", the Arguments property needs to be "loadscript.bat". 这就是您现在需要做的事情,FileName必须为“ cmd.exe”,Arguments属性必须为“ loadscript.bat”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.