[英]Exception while using exe in C#
我为Java代码创建了一个exe,并尝试在C#应用程序中使用它。 我正在这样使用
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "abc.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = args;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch (Exception ex)
{
// Log error.
MessageBox.Show(ex.Message);
}
在此之后,我读取了exe应该创建的文本文件。
System.IO.StreamReader file =
new System.IO.StreamReader(textFile);
但是在阅读文本文件“文件正在被另一个进程使用”时,我遇到了异常。
现在,我确定除了exe以外,没有其他进程正在访问该文件。 而且我还调用了WaitForExit()方法。 但是我还是例外。 有谁知道如何解决这个问题?
编辑:我通过删除文本文件并再次运行代码再次测试了代码。我得到了FileNotFound异常。所以似乎代码甚至在exe完成写入之前都试图读取文件。 我怎样才能强制仅在exe释放文件后才能读取文件?
您正在使用WaitForExit调用来阻止应用程序,从而阻止Windows处理UI事件。 我建议将您的代码移到其他这样的方法
编辑:因此,在运行abc或ebc之后,您可能没有其他代码可能太快了。
class Program
{
private static bool eventHandled;
private static int elapsedTime;
static void Main(string[] inputArgs)
{
string args = string.Empty;
try
{
Process exeProcess = new Process();
exeProcess.StartInfo.CreateNoWindow = false;
exeProcess.StartInfo.UseShellExecute = false;
exeProcess.StartInfo.FileName = "abc.exe";
exeProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
exeProcess.StartInfo.Arguments = args;
exeProcess.EnableRaisingEvents = true;
exeProcess.Exited += OnProcessExited;
exeProcess.Start();
}
catch (Exception ex)
{
// Log error.
Console.WriteLine(ex.Message);
}
// Wait for Exited event, but not more than 30 seconds.
const int SLEEP_AMOUNT = 100;
while (!eventHandled)
{
elapsedTime += SLEEP_AMOUNT;
if (elapsedTime > 30000)
{
break;
}
Thread.Sleep(SLEEP_AMOUNT);
}
}
private static void OnProcessExited(object sender, EventArgs eventArgs)
{
// do your work here
eventHandled = true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.