2016-07-08 20 views
4

Ich versuche eine try-catch-finally zu machen, damit, wenn das mainLog erfolgreich erstellt wurde, aber danach eine Ausnahme ausgelöst wurde, es ordnungsgemäß entsorgt wird. Wenn jedoch mainLog nicht erfolgreich erstellt wurde und ein mainLog.Dipose() Methodenaufruf existiert, wird eine weitere Ausnahme sein. Normalerweise würde ich eine if-Anweisung machen, aber DocX.Create() gibt kein bool zurück, also bin ich mir nicht sicher, wie ich das machen soll. Vielen Dank.C# Wie mache ich einen Try Catch Endlich ohne einen Bool, um Ressourcen freizusetzen?

public static string Check_If_Main_Log_Exists_Silent() 
    { 
     DocX mainLog; 
     string fileName = DateTime.Now.ToString("MM-dd-yy") + ".docx"; 
     string filePath = @"D:\Data\Main_Logs\"; 
     string totalFilePath = filePath + fileName; 

     if (File.Exists(totalFilePath)) 
     { 
      return totalFilePath; 
     } 
     else if (Directory.Exists(filePath)) 
     { 
      try 
      { 
       mainLog = DocX.Create(totalFilePath); 
       mainLog.Save(); 
       mainLog.Dispose(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("The directory exists but the log does not exist and could not be created. " + ex.Message, "Log file error"); 
       return null; 
      } 
     } 
     else 
     { 
      try 
      { 
       mainLog = DocX.Create(totalFilePath); 
       mainLog.Save(); 
       mainLog.Dispose(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("The directory and log does not exist and could not be created. " + ex.Message, "Log file error"); 
       return null; 
      } 
      finally 
      { 
       if(mainLog) 
      } 
     } 

    } 
+8

'using (var HauptLog = DocX.Create (totalFilePath)) {mainLog.Save(); } '. – GSerg

+0

sollten Sie Ihren Code versuchen zu vereinfachen - verwenden Sie eine temporäre Variable für die Nachricht. –

Antwort

6

Das Hinzufügen einer using statement wird nur dann absetzen, wenn sie am Ende des Codeblocks null ist. Es ist einer dieser handlichen syntaktischen Zucker.

4

Im allgemeinen Fall Sie mainLog auf null voreingestellt und nur die Methode aufrufen, wenn es nicht null ist. Mit C# 6 können Sie die handliche Form verwenden:

mainLog?.Dispose(); 

Für ältere Versionen eines einfachen, wenn:

if (mainLog != null) 
    mainLog.Dispose(); 

Wenn das Objekt implementiert die IDisposable Schnittstelle dann mit using Antwort zeigt die einfachste Art und Weise, wie Gaspa79 der ist.