Is it possible to force .NET to use the unicode version of P/Invoke method in its own code

Viewed 101

For example if i call the method System.IO.Directory.CreateDirectory, within the .NET code the Win32 API method CreateDirectory from kernel32.dll is called.

In the .NET source code the method is declared as following:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static extern bool CreateDirectory(
  string path,
  Win32Native.SECURITY_ATTRIBUTES lpSecurityAttributes);

CharSet is set to CharSet.Auto. It seems that always the Ansi version is called.

My question is if i can force .NET to use the unicode version instead of the Ansi version.

1 Answers

It seems that always the Ansi version is called.

How do you know this? Are you using .NET core on Linux or something? https://docs.microsoft.com/en-us/dotnet/standard/native-interop/charset

In any case, instead of this:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]

This:

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]

Alternatively, all Win32 APIs are really macros that map to either an A postfixed version of W postfixed version for ANSI and WIDE (unicode) respectively.

So calling CreateDirectoryW directly should work:

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
internal static extern bool CreateDirectoryW(
  string path,
  Win32Native.SECURITY_ATTRIBUTES lpSecurityAttributes);
Related