私はtry-catch-finallyを実行しようとしています。そのため、mainLogが正常に作成されたが、その後に例外がスローされた場合、適切に破棄されるようにします。ただし、mainLogがで、が正常に作成されておらず、mainLog.Dipose()
メソッド呼び出しが存在する場合は、の別の例外があります。通常、私はifステートメントを実行しますが、DocX.Create()
はboolを返さないので、これを行う方法がわかりません。ありがとうございました。あなたは、デフォルトでnull
にmainLog
を設定し、それがnullでない場合のみ、メソッドを呼び出す一般的なケースではC#最後にリソースを解放するブールなしで試してみましょう。
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)
}
}
}
'(var mainLog = DocX.Create(totalFilePath)){mainLog.Save();を使用します。 } '。 – GSerg
あなたはコードを試してみることを単純化するべきです - メッセージの一時変数を使用してください。 –