我正试图访问我的 Download
文件夹,并希望区分可能的错误,以便在出错时更好地通知用户,尤其是当 Windows Defender
干扰(见下文)。
我的代码基本上是这样的。
try
{
fileContents = File.ReadAllBytes(fileInfo.FullName);
}
catch (IOException ex)
{
if (ex != null && ex.Message.IndexOf("virus", StringComparison.OrdinalIgnoreCase) != -1)
{
myDataObject.ScanStatus = ScanStatusInfo.NotAccessable;
throw;
}
}
异常信息的字符串比较是我的肮脏的变通方法 Windows Defender
拦截对潜在感染文件的访问(你可以用例如 eicar测试病毒). 我想使用不同的(基于ID的)方法来处理这种情况,而不是依赖实际的消息字符串。
我根据以下信息,更新了我的方法。hresult.info
const uint ERROR_VIRUS_INFECTED = 0X800700E1;
[...]
try
{
fileContents = File.ReadAllBytes(fileInfo.FullName);
}
catch (IOException ex)
{
// This handles the case that Windows Defender stopped access to the file due to a virus.
// If this is the case, we won't get any access and throw the exception instead.
if (ex != null && (0xFFFF & ex.HResult) == (0XFFFF & ERROR_VIRUS_INFECTED))
{
myDataObject.ScanStatus = ScanStatusInfo.NotAccessable;
throw;
}
}
所以,这会告知用户问题中描述的情况,给出比 "莫名其妙我无法访问文件,我不知道为什么 "更多的信息,也允许从系统的本地语言中独立处理。