admin管理员组

文章数量:1402836

I have the following code:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetDllDirectory(string lpPathName);

string dllFolderPath= @"C:\temp\lib";

public static void Init()
{
    SetDllDirectory(dllFolderPath); // This works in debug but not in release mode
    
    // Do some stuff with a class that is loaded from the dll
    var myClass = new MyClass();
    ....
}

The code just imports some DLLs from the folder C:\temp\lib, and after importing, it instantiates an object of class MyClass that is defined in the loaded dll.

Now this works just fine when I am in debug mode, but it does not work in release mode.

When the program is at the line where MyClass should be instantiated, it crashes an the following error occurs:

System.IO.FileNotFoundException: The file or assembly "MyLib.dll" or a dependency could not be found.

PS: I have found out that when I turn off the option "Optimize Code" in release mode, it works. But I don't want to turn this feature off.

Any help is appreciated.

UPDATE: I have found a possible workaround by turning off the optimization for just that init method, where the dlls are loaded:

[MethodImpl(MethodImplOptions.NoOptimization)]
public static void Init()
{
    SetDllDirectory(dllFolderPath); // This works in debug but not in release mode

    // Do some stuff with a class that is loaded from the dll
    var myClass = new MyClass();
    ....
}

This tells the compiler to ignore optimization on that method while building the app.

本文标签: C amp NET 48DllImport does work in Debug mode but not in Release modeStack Overflow