以下代码是我们生产代码的一部分的简化摘录。它计算文件的 SHA256 哈希值并将其作为字符串返回,或者null
在文件无法访问时返回:
private static string CalculateHash(string fileName)
{
try
{
string result;
using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
{
byte[] data = File.ReadAllBytes(fileName);
result = BitConverter.ToString(sha256.ComputeHash(data));
}
Debug.WriteLine("Calculated hash for '" + fileName + "': " + result, 3);
return result;
}
catch (UnauthorizedAccessException ex)
{
Debug.WriteLine("The hash calculation failed: " + ex.Message, 3);
return null;
}
catch (IOException ex)
{
Debug.WriteLine("The hash calculation failed: " + ex.Message, 3);
return null;
}
}
我们的一位开发人员最近使用异常过滤器重构了代码以减少重复catch
块,所以它现在看起来像这样:
private static string CalculateHash(string fileName)
{
try
{
string result;
using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
{
byte[] data = File.ReadAllBytes(fileName);
result = BitConverter.ToString(sha256.ComputeHash(data));
}
Debug.WriteLine("Calculated hash for '" + fileName + "': " + result, 3);
return result;
}
catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException)
{
Debug.WriteLine("The hash calculation failed: " + ex.Message, 3);
return null;
}
}
然而,我们现在得到一个代码分析警告:
CA2000 - 在方法“CalculateHash(string)”中,在对对象“sha256”的所有引用超出范围之前调用 System.IDisposable.Dispose。
据我所知,SHA256CryptoServiceProvider
这里的处理是正确的,无论异常是否被过滤器捕获,都会发生这种情况。
这个 CA2000 是误报,还是异常过滤器创建了一个不会发生处置的场景?