Using a native Dll via LoadLibrary within ASP.NET runtime
I was recently debugging a code that was trying to load a native Dll using LoadLibrary within ASP.NET process. The code was trying a load native Dll and then dynamically invoke a method by name using GetProcAddress. The loadlibrary code was working as expected within a managed Dll and was also tested with in a console application. But it started throwing exception when it was used by the ASP.NET process. Debugged and figured out the exception was FileNotFoundException for loading the Dll via LoadLibrary. The Dll was copied into the bin folder in spite of it the ASP.NET runtime didn’t copy the Dll to the shadow location. After doing a research figured out the runtime would copy dependencies that have been referenced by the code and referenced via PInvoke, and that was the reason the Dll wasn’t copied.
So I had three choices
- Copy the native Dll’s to system32 directory – Certainly wasn’t a good idea
- Change the native code to implement COM – So that the Dll can be in any location and the ASP.NET can still load them. This wasn’t possible because we didn’t have source code
- Add the path of the Dll to the environment path variable – This was the most viable solution. The one drawback with this solution was if there was another native Dll with the similar name and if it was found in lookup then that would be loaded.
So we went ahead took the third option and renamed the Dll to include the organization name. The loadlibrary code within the ASP.NET runtime was able to locate the native Dll and load it.
FYI if the path environment variable is updated then the IIS has to be restarted to load the updated path variable.
Using a native Dll via LoadLibrary within ASP.NET runtime…
Thank you for submitting this cool story – Trackback from DotNetShoutout…
DotNetShoutout
May 26, 2010 at 9:11 pm
I am currently using VB.NET COM Class Library inside my web site via object tag and clsid. It is loading the COM correctly and also getting, setting the properties. Only issue I have is with LoadLibrary of kernel32.dll
Does it work inside a browser ?
I have added the native DLL in environment path variable
But still I am not getting the dll via LoadLibrary it returns zero
If I use LoadLibraryEx it returns me the pointer but then GetProcAddress returns me zero
Mahendra Bhatt
September 15, 2010 at 6:26 am