C #: how to find out the full path to the dll used in DllImport?

I imported the dll into my code:

[DllImport("dll.dll", CharSet = CharSet.Ansi)]
    private static extern int function(String pars, StringBuilder err);

I was wondering if the function works, but it is not inside the project, and not inside the Debug or Release folders. That is, "dll.dll" should not be available because it is not in the current project folder, however it is available. Now I want to know the full full path to the dll used at runtime, but I don’t know how to get it.

+5
source share
3 answers

You will need to use the win32 API.

First use GetModuleHandle , passing it "dll.dll". Then pass this handle to GetModuleFileName .

string GetDllPath()
{
      const int MAX_PATH = 260;
      StringBuilder builder = new StringBuilder(MAX_PATH);
      IntPtr hModule = GetModuleHandle("dll.dll");  // might return IntPtr.Zero until 
                                                    // you call a method in  
                                                    // dll.dll causing it to be 
                                                    // loaded by LoadLibrary

      Debug.Assert(hModule != IntPtr.Zero);
      uint size = GetModuleFileName(hModule, builder, builder.Capacity);
      Debug.Assert(size > 0);
      return builder.ToString();   // might need to truncate nulls
}

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

    [DllImport("kernel32.dll", SetLastError=true)]
    [PreserveSig]
    public static extern uint GetModuleFileName
    (
        [In] IntPtr hModule,        
        [Out] StringBuilder lpFilename,        
        [In][MarshalAs(UnmanagedType.U4)] int nSize
    );
+7
source

. Dynamic-Link - P/Invoke, , , DLL; -)


, , DLL . , P/Invoke LoadLibrary (, P/Invoke LoadLibraryEx LOAD_WITH_ALTERED_SEARCH_PATH) .

( . , / . YMMV.)

.

+4

If you really want to find out, use a dependency walker

It can even “control” your application at runtime and detect dynamic loads, so nothing remains hidden.

+1
source

All Articles