Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c#: how to know the full path of dll used in DllImport?

Tags:

c#

I've import dll in my code like that:

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

I was wondered that function works, but it is not inside project and not inside Debug or Release folders. I.e. "dll.dll" should not be availabe because it is not in the current project folder, however it IS available. Now I want to know the exact full path of the dll used at runtime, but don't know how to get it.

like image 534
Oleg Vazhnev Avatar asked Apr 02 '11 22:04

Oleg Vazhnev


1 Answers

You're going to have to use the win32 API.

First use GetModuleHandle passing "dll.dll" to it. Then pass that 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
    );
like image 73
dkackman Avatar answered Sep 19 '22 07:09

dkackman