WindowsのAPIであるGetShortPathName関数を利用する。
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern int GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
以下のように呼び出す。
// ※ポイント!
// 長いパスの先頭に「\\?\」をつけないと、短いパスを取得できない
var longPath = @"\\?\C:\Users\a\Desktop\あいうえお\テキストファイル\111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111.txt";
var shortPath = new StringBuilder(256);
if (GetShortPathName(longPath, shortPath, shortPath.Capacity) == 0)
{
// 取得失敗
}
else
{
// 取得成功。取得例 \\?\C:\Users\a\Desktop\あいう~1\テキス~1\111111~1.TXT
Console.WriteLine(shortPath);
}