首页 > 解决方案 > How to fetch the message string from Win32 provided HRESULT C#

问题描述

I'm curious if there is a function in C# to convert an Win32 HRESULT (long) error code gotten from unmanaged code into the representation string.

标签: c#hresult

解决方案


我不知道单个功能,但解决方法很简单。

public static string formatMessage( int hr ) =>
    Marshal.GetExceptionForHR( hr ).Message;

更新: “重复”问题非常不同。

HRESULT 代码记录在[MS-ERREF] 规范的第 2.1 节中

通过使用 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 );
}

推荐阅读