sczdavos
sczdavos

Reputation: 2063

How do I import .dll library from subfolder in C#

When I have the library in the same folder as app I can simply:

[DllImport("kernel32")]
public extern static IntPtr LoadLibrary(string librayName);

IntPtr iq_dll = LoadLibrary("IQPokyd.dll");

I also have this in my app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="plugins;" />
    </assemblyBinding>
  </runtime>
</configuration>

I'm able to load this library. Problem is that it is using some config files which needs to be in app run directory. Is there some possibility how to tell the library that files it needs are in the same folder as the library?

Upvotes: 3

Views: 2036

Answers (2)

Dmitry
Dmitry

Reputation: 14059

Since the DLL searches for the config in the current directory, it makes sense to temporarily change the current directory before loading it:

string saveCurDir = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(Path.Combine(Application.StartupPath, "plugins"));

IntPtr iq_dll = LoadLibrary("IQPokyd.dll");

Directory.SetCurrentDirectory(saveCurDir);

Upvotes: 2

Michael K.
Michael K.

Reputation: 74

You can do this by adding a probing tag to your app's .config file. For example, if you wanted libraries to be loaded from a /lib/ subdirectory, your config would look like this:

<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="lib"/>
    </assemblyBinding>
  </runtime>
</configuration>

Upvotes: 0

Related Questions