vineri, 31 august 2012

DllImport default path

When using DllImport for interop in C#, the default path of the library that you want to import is dictated by the operating system. The search order used by Windows OS depends on whether SafeDllSearchMode is enabled or disabled. When the safe mode is enabled, the current directory is placed lower in the search order. See http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v=vs.85).aspx for complete information on Dinamyc-Link Library Search Order.

Beside the implicit search order described below, one can use the .dll full path with the DllImport attribute.

The search order when safe mode is enabled is:

1.The directory from which the application loaded.

2.The system directory. Use the GetSystemDirectory function to get the path of this directory.

3. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.

4.The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

5.The current directory.

6.The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.

And when the safe mode is disabled:

1.The directory from which the application loaded.

2.The current directory.

3.The system directory. Use the GetSystemDirectory function to get the path of this directory.

4. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.

5.The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

6.The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.

I have successfully used the directory from which the application is loaded, but it will be interesting to give a try to the other modes. Probably the most efficient is the use the first option most of the time for better performance, just because it's the first place the OS looks for the .dll. Knowing where the OS will look for the .dll is essential and a point to remember.