gpt4 book ai didi

C# 如何在没有 bool 的情况下执行 Try Catch Finally 来释放资源?

转载 作者:太空狗 更新时间:2023-10-30 00:18:21 26 4
gpt4 key购买 nike

我正在尝试执行 try-catch-finally,这样如果 mainLog 已成功创建,但之后抛出异常,它将被正确处理。但是,如果 mainLog 成功创建并且存在 mainLog.Dipose() 方法调用,则会出现另一个异常。通常,我会执行 if 语句,但 DocX.Create() 不会返回 bool,因此我不确定如何执行此操作。谢谢。

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

}

最佳答案

添加 using statement仅当代码块末尾为 null 时才会调用 dispose。它是那些方便的语法糖之一。

关于C# 如何在没有 bool 的情况下执行 Try Catch Finally 来释放资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38274372/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com