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.
Asked
Active
Viewed 1,292 times
3
-
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 Mar 29 '13 at 15:38
-
@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 Mar 29 '13 at 15:40
-
1@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 Mar 29 '13 at 15:41
-
Does this answer your question? [How to determine whether a DLL is a managed assembly or native (prevent loading a native dll)?](https://stackoverflow.com/questions/367761/how-to-determine-whether-a-dll-is-a-managed-assembly-or-native-prevent-loading) – MSDN.WhiteKnight Jul 31 '23 at 05:39
1 Answers
4
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.

Reed Copsey
- 554,122
- 78
- 1,158
- 1,373
-
-
@DavidThielen No - unfortunately, there's no simple API for this, even in the native side. – Reed Copsey Mar 29 '13 at 15:42
-
@DavidThielen before you go off coding a way to do this, think about the times involved. If handling the exception adds maybe 2ms to the build time instead of writing out a way to parsing the PE header just do a little math if `(Time involved to write the handler / Time difference between exception handling and detecting) < Number of builds in the lifetime of the program` its not worth doing. – Scott Chamberlain Mar 29 '13 at 15:45