3
votes

How can I, in a program, determine if a DLL is managed or unmanaged code? We're using this code to make sure all of our managed DLLs are MSIL. But it throws an exception on unmanaged DLLs so I need a way to first check if a DLL is managed.

1
How often are you doing it? Sometimes you just need to handle the exception and move on, I don't know if there is a easy (exceptionless) way to solve this.Scott Chamberlain
@ScottChamberlain It's in the build process so not a big time hit. I just dislike having exceptions when code is running as expected.David Thielen
@DavidThielen There are ways to do it, but it's a bit complicated, since there's no direct API. Personally, catching the exception is that approach I'd take, since it's just easy and cleaner...Reed Copsey

1 Answers

4
votes

The simplest option would most likely be to just try to open the file as you are, and catching the exception. Any unmanaged assembly will throw an exception on Assembly.LoadFrom.

However, if you want to determine this more rigorously, you'd need to examine the PE header for the appropriate information yourself. This article describes the process in detail, but it requires checking the IMAGE_OPTIONAL_HEADER structure of the PE header of the DLL.