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

2

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?

c#
.net
.net-standard
hresult
asked on Stack Overflow Sep 23, 2017 by NightOwl888 • edited Sep 23, 2017 by NightOwl888

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0