How do I make catching generic IOExceptions reliably portable across platforms?

折月煮酒 提交于 2019-12-11 07:06:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!