GetShortPathNameW 找不到指定的文件
本文关键字:文件 找不到 GetShortPathNameW | 更新日期: 2023-09-27 18:31:12
我正在尝试获取包含宽字符的路径的短路径名,这是我使用的代码,它总是为找不到文件抛出异常。 文件肯定存在,我做错了什么?
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace GetShortPathNameW_Test
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int GetShortPathNameW(String pathName, System.Text.StringBuilder shortName, int cbShortName);
static void Main(string[] args)
{
System.Text.StringBuilder new_path = new System.Text.StringBuilder(1500);
int n = GetShortPathNameW("''''?''C:''''temp''test1.txt", new_path, 1024);
if (n == 0)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
}
显式调用 Unicode 版本GetShortPathNameW
,但没有指定用于调用 Unicode 版本的正确参数。
首先,将方法重命名为 GetShortPathName
。这足以让它开始工作,而无需任何其他更改。您的参数仍然是"ANSI"字符串,但这没关系,因为您正在调用"ANSI"实现。
其次,可以将CharSet = CharSet.Unicode
添加到 DllImport
属性中,以指定需要 Unicode 实现。这也确保了字符串作为 Unicode 字符串传递。这也将使一切按预期工作。
如今,应该没有理由不调用函数的 Unicode 实现,但是 DllImport
的默认值无法在不破坏向后兼容性的情况下更改,因此需要为每个函数指定它。