2013-03-19 3 views
1

데이터베이스 데이터에서 Excel 파일을 생성 할 수있는 Windows Form 응용 프로그램을 만들고 있습니다. 데이터베이스에 파일을 채우고 난 후 파일을 열고 매크로를 실행하여 파일을 저장 한 다음 닫습니다 (또는 내가 닫을 것으로 생각합니다). 이 파일은 내 HDD에 저장되지만 모든 파일이 생성되면 새 파일 세트를 생성 할 수 있어야하므로 새 세트를 생성하기 전에 내 HDD에서 모든 이전 파일을 삭제해야합니다. 응용 프로그램을 한 번 실행 한 후 새 파일 집합을 생성하려고하면 파일 중 하나 (첫 번째 배치에서 생성 된 마지막 파일)가 다른 프로세스에서 사용되었다는 오류가 발생합니다. 여기Excel 파일을 만들고 편집 한 후 릴리스

내 코드입니다 : 응용 프로그램이 파일을 해제하지 않기 때문에 내가 잘못하고있는 무슨

public void RemoveRows_Macro(string fileName) 
{ 

    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 
    Microsoft.Office.Interop.Excel.Workbook xlWorkBook; 
    xlWorkBook = xlApp.Workbooks.Open(fileName); 
    //xlApp.Visible = true; 
    xlApp.DisplayAlerts = true; 

    //Run the macro 
    xlApp.Run("RemoveRows", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 

    xlWorkBook.Save(); 

    xlWorkBook.Close(false); 
    xlApp.Quit(); 
    releaseObject(xlApp); 
    releaseObject(xlWorkBook); 
} 

private void releaseObject(object obj) 
{ 
    try 
    { 
     System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); 
     obj = null; 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine("Error in releasing object :" + ex); 
     obj = null; 
    } 
    finally 
    { 
     GC.Collect(); 
    } 
} 

?

답변

1
finally 
{ 
    GC.Collect(); 
    GC.WaitForPendingFinalizers(); 
} 
+0

미안하지만 잘못 입력했습니다! 나는 지금 그것을 시도하고있다. – Lahib

+0

편집 내 대답 – TalentTuner

+0

그것은 효과가있다. 도움에 감사드립니다. 감사합니다. – Lahib

0

지금 테스트를 실행할 수 없지만 xlApp 및 xlWorkBook을 releaseObject에 전달하기 전에 null로 설정 한 것처럼 보입니다. 그 후 다른 이유가있을 수 있습니다.

+0

을 수행 할 때이 링크를 훌륭한 자원을 발견했다. – Lahib

0

먼저 xlApp 및 xlWorkBook을 null로 설정 한 다음 해제하려고 시도합니다. 이 두 줄을 주석으로 처리하십시오.

xlApp = null; 
xlWorkBook = null; 

문제가 해결 되었습니까?

+0

바로 시도해 보았습니다. 문제를 해결하지 못했습니다. 마지막으로 생성 된 파일을 여전히 잠근다 – Lahib

2

개체를 먼저 해제 한 다음 개체를 할당 한 순서의 역순으로 null로 설정할 수 있습니다.

releaseObject(xlWorkBook); 
releaseObject(xlApp); 
xlWorkBook = null; 
xlApp = null; 

나는 내가 2 개 라인을 제거하고 여전히 마지막으로 생성 된 파일을 해제하지 않습니다 엑셀 Interop를 How do I properly clean up Excel interop objects?

+0

링크를 제공해 주셔서 감사합니다. 도움 감사 – Lahib

관련 문제