Edit

Share via


Specifying DllImportSearchPath.AssemblyDirectory only searches the assembly directory

Starting in .NET 10, if you specify DllImportSearchPath.AssemblyDirectory as the only search flag, the runtime searches exclusively in the assembly directory. This change affects the behavior of P/Invokes and the NativeLibrary class.

Version introduced

.NET 10 Preview 5

Previous behavior

When DllImportSearchPath.AssemblyDirectory was specified as the only search flag, the runtime searched the assembly directory first. If the library was not found, it fell back to the operating system's default library search behavior.

For example, with the following code, the runtime would search the assembly directory and then fall back to the OS search paths.

[DllImport("example.dll", DllImportSearchPath = DllImportSearchPath.AssemblyDirectory)]
public static extern void ExampleMethod();

New behavior

When DllImportSearchPath.AssemblyDirectory is specified as the only search flag, the runtime searches only in the assembly directory. It doesn't fall back to the operating system's default library search behavior.

The previous code example now only searches the assembly directory for example.dll. If the library is not found there, a DllNotFoundException is thrown.

Type of breaking change

This is a behavioral change.

Reason for change

The fallback behavior when specifying DllImportSearchPath.AssemblyDirectory caused confusion and was inconsistent with the design of search flags. This change ensures clarity and consistency in behavior.

If fallback behavior is required, avoid specifying an explicit DllImportSearchPath. By default, when no flags are specified, the runtime searches the assembly directory and then falls back to the operating system's default library search behavior.

Example:

[DllImport("example.dll")]
public static extern void ExampleMethod();

Affected APIs

See also