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)
}
}
}
'using (var HauptLog = DocX.Create (totalFilePath)) {mainLog.Save(); } '. – GSerg
sollten Sie Ihren Code versuchen zu vereinfachen - verwenden Sie eine temporäre Variable für die Nachricht. –