2014-05-19 47 views
-1

當創建一個簡單的winform(將excel值讀取到標籤&文本框中)時,我遇到了這個錯誤:進程無法訪問文件'C:\ Locations.xlsx',因爲它是被另一個進程使用。在應用程序崩潰時釋放Excel.Applicationcom對象

我只是調試來檢查我的Excel文件的連接... :(

Excel.Application excelApp = new Excel.Application(); 
excelApp.Visible = false; 
string workbookPath = tpath; 
try 
{ 
    Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 
        0, true, 5, "", "", false, Excel.XlPlatform.xlWindows, "", 
        true, true, 0, true, false, false); 
    Excel.Sheets excelSheets = excelWorkbook.Worksheets; 
    Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item("Check"); 
    Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("A1", "I11"); 

然後我意識到COM對象不能被釋放bcoz我只是測試代碼的連通性。這使得我覺得如果應用程序崩潰,需要釋放com對象...當應用程序啓動時,該文件被複制到硬盤上,並在應用程序關閉時被刪除,所以還需要在文件加載之前檢查是否釋放對象bcoz文件

BTW Marshal.ReleaseComObject("Check");也無濟於事

任何幫助。

編輯: 這個getdb代碼進入主表單加載的第一行。

  private void getdb() 
    { 
     try 
     { 
      if (File.Exists(tpath)) 
      { 
       File.Delete(tpath); 
      } 
      else 
      { 
       string spath = textBox1.Text.ToString() + "\\Locations.xlsx"; 
       File.Copy(spath, tpath, true); 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message + "\nSource: " + ex.Source + "\n" + ex.ToString(), "Database File Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 
+0

那你的意思是「崩潰」?有沒有未處理的異常?你有一個'try'塊,那裏面拋出的異常會發生什麼? –

+0

@BenAaronson崩潰=無需爲excel過程添加/應用適當的結束代碼...我只是將它調試成一半編碼,並且自那時起,該過程被凍結並顯示「正在使用」。 – gsvirdi

回答

0

這是我如何關閉它在我的應用程序:

[DllImport("user32.dll")] 
private static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out IntPtr ProcessId); 

//close excel by the interface functions 
excelWorkbook.Close(true, filepath, Missing.Value); 
excelApp.Quit() 

// kill the curent excel instance due to the fact that not always the curent object gets released 
IntPtr hwnd = new IntPtr(excelApp.Hwnd); 
IntPtr processId; 
IntPtr foo = GetWindowThreadProcessId(hwnd, out processId); 
Process proc = Process.GetProcessById(processId.ToInt32()); 
proc.Kill(); 
+0

我正在考慮dispose方法的正確使用/位置。我將xlsx文件從網絡複製到用戶桌面,並在複製之前檢查現有文件並將其刪除。我不知道這個應用程序何時可能面臨同樣的問題,因此無法在用戶端刪除現有文件引發問題。 SoI想知道我在哪裏使用dispose方法,以及如何處理? (在我的問題中包含簡單的文件IO代碼,在我的主表單加載函數的第一行使用它) – gsvirdi

相關問題