Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How do I do a Try Catch Finally without a bool to free up resources?

I'm trying to do a try-catch-finally so that if the 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 there exists a mainLog.Dipose() method call, there will be another exception. Typically, I would do an if statement but DocX.Create() does not return a bool so I'm not sure how to do this. Thank you.

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

    }
like image 782
the_endian Avatar asked Dec 25 '22 03:12

the_endian


1 Answers

Adding a using statement will call dispose only if it's null at the end of the code block. It's one of those handy syntactic sugars.

like image 97
Gaspa79 Avatar answered Jan 04 '23 22:01

Gaspa79