Load native libraries from a dynamic location

Today, I had to deal with an uncommon need. In short, the idea is to download a native library (dll) into a temporary directory (not in the application folder), and use its methods. The content of the dll is known, so I want to use the DllImport attribute to easily call the methods of the dll.

The application must work on Windows 10, so I can use a function introduced in Windows 8 AddDllDirectory. This function allows to indicate the paths where the native libraries are. So, you can download the dll and use the AddDllDirectory function to add its path for dll loading.

const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000;

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetDefaultDllDirectories(uint DirectoryFlags);

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern int AddDllDirectory(string NewDirectory);

void Initialize()
{
    var downloadDirectory = "temp";
    DownloadDll(downloadDirectory);

    // Indicate to search libraries in
    // - application directory
    // - paths set using AddDllDirectory or SetDllDirectory
    // - %windows%\system32
    SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);

    // Add the directory of the native dll
    AddDllDirectory(downloadDirectory);

    // Use the native dll
    MyMethod();
}

[DllImport("mydll.dll")]
public static extern int MyMethod();

More information about the kernel32 methods: