.NET Standard 是否在它支持的每个平台上标准化 HResult 值?

Does .NET Standard normalize HResult values across every platform it supports?

我正在创建一个创建随机文件的简单函数。为了线程安全,它在重试循环中创建文件,如果文件存在,它会再次尝试。

while (true)
{
    fileName = NewTempFileName(prefix, suffix, directory);

    if (File.Exists(fileName))
    {
        continue;
    }

    try
    {
        // Create the file, and close it immediately
        using (var stream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
        {
            break;
        }
    }
    catch (IOException e)
    {
        // If the error was because the file exists, try again
        if ((e.HResult & 0xFFFF) == 0x00000050)
        {
            continue;
        }

        // else rethrow it
        throw;
    }
}

根据 MSDN,HResult 值是从 COM 派生的,这似乎表明它只适用于 Windows,并且 specifically lists them as "Win32 codes". But this is in a library which targets .NET Standard and ideally it should work on every platform .NET Standard supports

我想知道我是否可以依靠上述使用 HResult 的值的方法来实现跨平台? documentation在这一点上不清楚。

如果不是,我如何确定在其他平台上期望的 HResult 值?

NOTE: There is a similar question Does .NET define common HRESULT values?, but it was asked before .NET Standard (and cross-platform support for .NET) existed, so I cannot rely on that answer for this purpose.

目前,我们的代码库仅使用:

  1. 0x00000020 - ERROR_SHARING_VIOLATION
  2. 0x00000021 - ERROR_LOCK_VIOLATION
  3. 0x00000050 - ERROR_FILE_EXISTS

我们的目标是 .NET Standard 1.5。

NOTE: While the accepted answer does satisfy what I asked here, I have a follow-up question How do I make catching generic IOExceptions reliably portable across platforms?

Exception.HResult 值未跨平台标准化。

对于 I/O 错误,.NET Core 将 return 平台特定错误代码作为 HResult。您的示例中已存在文件的 HResult 属性 的值在 Linux 上将为 17,对于其他 Unix 系统可能是不同的值。

将IO错误映射到Unix上的异常的相关代码在这里:https://github.com/dotnet/corefx/blob/master/src/Common/src/Interop/Unix/Interop.IOErrors.cs