views:

142

answers:

2

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

+2  A: 

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:

string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
Console.WriteLine(errorMessage);
Nick Meyer
http://www.pinvoke.net/default.aspx/kernel32/FormatMessage.html Says never to use FormatMessage
Malfist
@Malfist, thanks for pointing that out. There is a reply there that says it's okay as long as you're using Marshal.GetLastWin32Error to retrieve the error code. Nonetheless, it looks like Win32Exception is a better solution.
Nick Meyer
A: 

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.

Jon Norton
Or just do what Nick said :-)
Jon Norton
I don't see this. And this doesn't help me display anything to the user.
Malfist