【问题标题】:How to fetch the message string from Win32 provided HRESULT C#如何从 Win32 提供的 HRESULT C# 中获取消息字符串
【发布时间】:2020-11-26 16:28:15
【问题描述】:

我很好奇C# 中是否有一个函数可以将从非托管代码中获取的 Win32 HRESULT (long) 错误代码转换为表示 string

【问题讨论】:

    标签: c# hresult


    【解决方案1】:

    我不知道单个函数,但解决方法很简单。

    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 );
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多