7

I am new in dotnet.I have a dotnet dll that loads a c dll by using DllImport. I want to place all the dlls in a folder which is diffrent from the location of application. I dont want to modify environmental variables. So i used setdlldirectory API and load my c# assembly through Assembly.Loadfrom(..). I checked that SetdllDirectory is working fine by verifying the value of GetDllDirectory(..). But it is neither loading C# dll nor c dll from that folder. I am able to load C# dll by specyfing the path in Assembly.Loadfrom. But not able to load c dll.

Thanks in advance!!

Prateek Singh
  • 863
  • 1
  • 8
  • 28
Rohit Garg
  • 101
  • 1
  • 2
  • 5

2 Answers2

16

I'd suggest adding the directory path to PATH env variable in runtime, using the following code:

var dllDirectory = @"C:/some/path";
Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";" + dllDirectory);

That way, the change is only affecting the running process and is discarded when it exits.

Tomek
  • 785
  • 4
  • 10
  • Actually i dont want to modify any environment variable. Is there any way that C# dll and c # dll loaded from the path specified in SetDllDirectory?? – Rohit Garg Jul 11 '12 at 04:28
  • It's the easiest way, you don't have to use SetDllDirectory at all. Path set via SetDllDirectory function will not be used when you're loading dlls via .NET interop (DllImport), you have to use LoadLibrary (kernel32.dll) to obtain a function pointer and then use marshalling to obtain delegates to functions from that dll. This might be helpul: http://stackoverflow.com/a/1750938/1515409 – Tomek Jul 11 '12 at 05:50
  • Tomek, I am quite certain SetDllDirectory will affect where PInvoke DLLs are loaded from. – Cameron Oct 06 '15 at 04:24
0

Take a look at the documentation for LoadFrom and you'll find that it says: If a native image exists for assemblyFile, it is not used. The assembly cannot be loaded as domain neutral.

I believe you're going to need to add the DLL directory to the EXE's path.

Carey Gregory
  • 6,836
  • 2
  • 26
  • 47