簡體   English   中英

在C#中使用exe時發生異常

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM