使用 C# 调用外部 .exe 时出现问题
我试图从我的 C# 代码运行这个 .exe 文件,它确实调用了 .exe 文件,但随后它在中途崩溃。如果我单击资源管理器上的 .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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,这正在造成僵局,这可能是最终崩溃的问题。删除睡眠并尝试以下操作:
请参阅此问题的答案以获取解释:
重定向输出时 ResGen.exe 卡住
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:
Please see the answer to this question for an explanation:
ResGen.exe stucks when redirect output
这要求您指定 .exe 文件的名称。将其设置为 true 时,将使用另一个 Windows 函数来启动该文件,它足够聪明地发现 .bat 文件需要启动 cmd.exe 来解释 .bat 文件中的命令。
这就是您现在需要自己做的,文件名必须是“cmd.exe”,参数属性需要是“loadscript.bat”。
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".