【发布时间】:2016-07-08 19:49:02
【问题描述】:
我正在尝试做一个 try-catch-finally,以便如果 mainLog 成功创建,但之后抛出异常,它将被正确处理。但是,如果 mainLog 没有成功创建并且存在mainLog.Dipose() 方法调用,则会出现另一个异常。通常,我会做一个 if 语句,但 DocX.Create() 不会返回布尔值,所以我不知道该怎么做。谢谢。
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 (var mainLog = DocX.Create(totalFilePath)) { mainLog.Save(); }. -
您应该简化以保持您的代码尝试 - 为消息使用临时变量。
标签: c# try-catch try-catch-finally