Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 look these up within the program? Forexample, if I get error 1017. Can I tell the user

The system has attempted to load or restore a file into the registry, but the specified file is not in a registry file format. (ERROR_NOT_REGISTRY_FILE: 0x3F9)

Instead of

Error Code: 1017

like image 469
Malfist Avatar asked Oct 30 '09 16:10

Malfist


People also ask

Why are error codes in hexadecimal?

Errors. Hex is often used in error messages on your computer. The hex number refers to the memory location of the error. This helps programmers to find and then fix problems.

What is System Error Code?

A system error code is an error number, sometimes followed by a short error message, that a program in Windows may display in response to a particular problem it's having.


2 Answers

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); 
like image 34
flapster Avatar answered Sep 23 '22 00:09

flapster


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); 
like image 178
Nick Meyer Avatar answered Sep 25 '22 00:09

Nick Meyer