我正在创建一个创建随机文件的简单函数。为了线程安全,它在重试循环中创建文件,如果文件存在,它会再次尝试。
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.
目前,我们的代码库仅使用:
- 0x00000020 - ERROR_SHARING_VIOLATION
- 0x00000021 - ERROR_LOCK_VIOLATION
- 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/