问题
I was trying to make the below code work on .NET Standard 1.5, which implies it should be portable across all platforms .NET Standard 1.5 supports.
try
{
channel = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
}
catch (IOException e) when ((e.HResult & 0xFFFF) == 0x00000020) // ERROR_SHARING_VIOLATION
{
// no failure reason to be recorded, since this is the expected error if a lock exists
}
catch (IOException e)
{
FailureReason = e;
}
catch (UnauthorizedAccessException e)
{
// On Windows, we can get intermittent "Access
// Denied" here. So, we treat this as failure to
// acquire the lock, but, store the reason in case
// there is in fact a real error case.
FailureReason = e;
}
However, I have discovered when asking Does .NET Standard normalize HResult values across every platform it supports? that Exception.HResult
cannot be used reliably across platforms. Now I am stuck.
What alternative to HResult is there for determining what type of exception was thrown when the .NET type is simply IOException
? In other words, how do I reliably determine whether the error is a sharing violation (Windows: 0x00000020
) or a lock violation (Windows: 0x00000021
) so it can be distinguished from an IOException
I am not interested in?
来源:https://stackoverflow.com/questions/46382637/how-do-i-make-catching-generic-ioexceptions-reliably-portable-across-platforms