Getting the Windows System Error Code title/description from its hex number

后端 未结 4 1328
孤城傲影
孤城傲影 2020-12-13 07:00

I\'m messing around with some windows functions using p/invoke. Occasionally, I get an error code that is not ERROR_SUCCESS (such an odd name).

Is there a way to loo

相关标签:
4条回答
  • 2020-12-13 07:27

    I landed on this page while in search of a managed alternative to calling FormatMessage through P/Invoke.

    As others have said, there is no way to get those capitalized, underscored names, short of looking them up in winerror.h, which I have seen reproduced online in various places where I landed in the course of searching for information about resolving specific status codes. A quick Google search, for winerror.h, itself, uncovered a page, at Rensselaer Polytechnic Instutute, where someone has helpfully extracted the #define statements from it.

    Looking at it gave me an idea; I think there may be a way to get there, working from the source code of winerror.h, which I have, as part of the Windows Platform SDK that ships with every recent version of Microsoft Visual Studio.

    Right now, I am in the middle of sorting out a pressing issue in the .NET assembly that brought me to this page. Then, I'll see what I can cobble together; this kind of challenge is right up my alley, and somebody threw down a gauntlet.

    0 讨论(0)
  • 2020-12-13 07:29

    Yes there's a function that does that but I don't remember what it is. In the mean time, you can use the error lookup tool (Tools->Error Lookup) to see what a particular code means from within Visual Studio.

    0 讨论(0)
  • 2020-12-13 07:34

    I'm not sure if there's a niifty .NET wrapper, but you could call the FormatMessage API using P/Invoke.

    See this answer for how it would normally be called from native code. Though the question refers to grabbing error codes from HRESULTs, the answer also applies for retreiving codes from the regular OS error codes coming from GetLastError/GetLastWin32Error).

    EDIT: Thanks Malfist for pointing me to pinvoke.net, which includes alternative, managed API:

    using System.ComponentModel;
    
    string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
    Console.WriteLine(errorMessage);
    
    0 讨论(0)
  • 2020-12-13 07:41

    You could take the defines from winerror.h at Rensselaer Polytechnic Institute, and put them into an Enum:

    public enum Win32ErrorCode : long
    {
         ERROR_SUCCESS = 0L,
         NO_ERROR = 0L,
         ERROR_INVALID_FUNCTION = 1L,
         ERROR_FILE_NOT_FOUND = 2L,
         ERROR_PATH_NOT_FOUND = 3L,
         ERROR_TOO_MANY_OPEN_FILES = 4L,
         ERROR_ACCESS_DENIED = 5L,
         etc.
    }
    

    Then if your error code is in a variable error_code you would use :

    Enum.GetName(typeof(Win32ErrorCode), error_code);
    
    0 讨论(0)
提交回复
热议问题