【发布时间】:2020-11-26 16:28:15
【问题描述】:
我很好奇C# 中是否有一个函数可以将从非托管代码中获取的 Win32 HRESULT (long) 错误代码转换为表示 string。
【问题讨论】:
我很好奇C# 中是否有一个函数可以将从非托管代码中获取的 Win32 HRESULT (long) 错误代码转换为表示 string。
【问题讨论】:
我不知道单个函数,但解决方法很简单。
public static string formatMessage( int hr ) =>
Marshal.GetExceptionForHR( hr ).Message;
更新:“重复”问题非常不同。
HRESULT 代码记录在 section 2.1 of the [MS-ERREF] spec 中。
通过使用 Severity=1 和 Facility=FACILITY_WIN32,可以将任何 Win32 代码打包到 HRESULT 中。反之则不然,FACILITY_WIN32 只是众多之一。使用Win32Exception 的“重复”问题的公认答案不适用于此问题。
这是一个快速演示。
static void testHresultMessages()
{
int hr = new OverflowException().HResult;
// Prints "Unknown error (0x80131516)"
Console.WriteLine( new Win32Exception( hr ).Message );
// Prints "Arithmetic operation resulted in an overflow."
Console.WriteLine( Marshal.GetExceptionForHR( hr ).Message );
}
【讨论】: