NetInverse Developers Blog

March 8, 2009
Category: .Net — Tags: , , , , — admin @ 1:00 am

In C++, you can use Win32 WPI FormatMessage to get the system error message. So what is the equivalent in managed code?

It is easy! you can simply use Marshal.GetExceptionForHR.

Marshal.GetExceptionForHR Method (Int32):
Converts the specified HRESULT error code to a corresponding Exception object.

Namespace: System.Runtime.InteropServices
Assembly: mscorlib (in mscorlib.dll)

Sample code:

using System;
using System.Text;
using System.Runtime.InteropServices;

namespace hr
{
    class Program
    {
        static void Main(string[] args)
        {
            Exception e = Marshal.GetExceptionForHR(-2147024894);
            System.Console.WriteLine(e.Message);
        }
    }
}

Run above program you will get following system error message from the console:

The system cannot find the file specified. (Exception from HRESULT: 0×80070002)

Please note that when you call a COM object and want to get back the original HResult like S_OK and S_FLASE, you may need to use PreserveSigAttribute Class. Since most COM member return an HRESULT, by applying the PreserveSigAttribute, you can retrieve an integer representing the success or failure HRESULT.

©2009 NetInverse. All rights reserved. Powered by WordPress