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

标签 c# .net .net-standard hresult

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

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" .但这是在一个以 .NET Standard 为目标的库中,理想情况下它应该适用于 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 将返回特定于平台的错误代码作为 HResult。您的示例中已存在文件的 HResult 属性值在 Linux 上将为 17,对于其他 Unix 系统它可能是不同的值。

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

关于c# - .NET Standard 是否在它支持的每个平台上标准化 HResult 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46380483/

相关文章:

c# - 从 C# 调用具有函数参数的 F# 函数

c# - 在 C# 中使用按钮清除多个文本框

c# - 移位运算符 >> 或 << 何时有用?

.net - 是否有一个 .Net StyleCop 规则会警告锁(this)、锁(typeof、lock(<string obj> 等)?

odbc - AWS RedShift - .NET Core(ODBC 支持?)

c# - 如何获取服务器IP地址(在C#/asp.net中)?

c# - 如何以编程方式调用 Windows 权限对话框?

c# - 将通用接口(interface)的实现分配给属性

vb.net - System.Security.Cryptography.MACTripleDES() 未在 .NET 标准中定义

c# - 从 C# Azure 函数引用 System.Data.SqlClient 时修复 PlatformNotSupportedException