C # How to make Try Catch Finally without bool to free resources?

I am trying to do try-catch-finally so that if mainLog was successfully created, but an exception was thrown after that, it will be disposed of properly. However, if mainLog was not successfully created and a method call exists mainLog.Dipose(), another exception will occur. Normally, I would do an if statement, but it DocX.Create()does not return bool, so I'm not sure how to do this. Thank.

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)
            }
        }

    }
+4
source share
2 answers

Adding an instruction will only call dispose if it is not listed at the end of the code block. This is one of those convenient syntactic sugars.

+6

mainLog null , null. # 6 :

mainLog?.Dispose();

, :

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

IDisposable, using , Gaspa79.

+4

All Articles