Nig*_*888 7 .net c# hresult .net-standard
我正在创建一个创建随机文件的简单函数.为了线程安全,它在重试循环中创建文件,如果文件存在,则再次尝试.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
根据MSDN,HResult值来自COM,它似乎表明它只能在Windows上运行,它特别将它们列为"Win32代码".但是这是一个面向.NET Standard的库,理想情况下它应该适用于.NET Standard支持的每个平台.
我想知道的是,我是否可以依赖上述使用HResult值的跨平台方法?关于这一点,文档并不清楚.
如果没有,我如何确定在其他平台上期望的HResult值?
注意:有一个类似的问题.NET是否定义了常见的HRESULT值?但是在.NET Standard(以及.NET的跨平台支持)存在之前就被问到了,所以我不能为此目的而依赖这个答案.
目前,我们的代码库仅使用:
我们的目标是.NET Standard 1.5.
注意:虽然接受的答案确实满足了我在这里提出的要求,但我有一个后续问题如何使跨平台可靠地移植通用IOExceptions?
Exception.HResult值不是跨平台标准化的.
对于I/O错误,.NET Core将返回特定于平台的错误代码作为HResult.您的示例中已存在的文件的HResult属性值在Linux上为17,对于其他Unix系统可能是不同的值.
将IO错误映射到Unix上的异常的相关代码如下:https://github.com/dotnet/corefx/blob/master/src/Common/src/Interop/Unix/Interop.IOErrors.cs