GetShortPathNameW无法找到指定的文件

时间:2014-11-19 10:57:36

标签: c#

我正在尝试获取包含宽字符的路径的短路径名称,这是我正在使用的代码,它始终为未找到的文件抛出异常。该文件肯定存在,我做错了什么?

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());
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您显式调用Unicode版本GetShortPathNameW,但未指定用于调用Unicode版本的正确参数。

首先,将方法重命名为GetShortPathName。这足以让它开始工作,没有任何其他变化。您的参数仍然是“ANSI”字符串,但这没关系,因为您正在调用“ANSI”实现。

其次,您可以将CharSet = CharSet.Unicode添加到DllImport属性中,以指定您想要Unicode实现。这也确保字符串作为Unicode字符串传递。这也将使一切按预期工作。

现在,没有理由不调用函数的Unicode实现,但DllImport的默认值不能在不破坏向后兼容性的情况下改变,因此需要为每个函数指定它。

相关问题