5

我有一个简短版本或 DOS 格式的路径(例如“C:/DOCUME~1”)并且想要获取它的完整路径/长路径(例如“C:/Documents And Settings”)。

我试过 GetLongPathName api。有效。但是当处理 unicode 文件名时,它会失败。

Private Declare Function GetLongPathName Lib "kernel32" Alias _
    "GetLongPathNameA" (ByVal lpszShortPath As String, _
    ByVal lpszLongPath As String, ByVal cchBuffer As Long) As Long

我尝试为 GetLongPathNameW 取别名,但它似乎什么都不做,对于 Unicode 和非 Unicode 文件名,总是返回 0。在 MSDN 中只有一篇关于 C/C++ 的 GetLongPathNameW 的文章,而不是任何 VB/VBA 的文章。我可以做错什么吗?

这种情况有什么解决办法吗?我在 Google 和 StackOverflow 上花了几个小时,但找不到。

问候,

4

2 回答 2

4

这对你有用吗?我已将文件路径转换为短路径名,然后再次将其转换回来,即使是 unicode(例如 C:/Tö+)也会给出正确的字符串

Private Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" _
    (ByVal lpszLongPath As String, ByVal lpszShortPath As String, ByVal lBuffer As Long) As Long
Private Declare Function GetLongPathName Lib "kernel32" Alias "GetLongPathNameA" _
    (ByVal lpszShortPath As String, ByVal lpszLongPath As String, ByVal cchBuffer As Long) As Long

Public Function GetShortPath(ByVal strFileName As String) As String
    'KPD-Team 1999
    'URL: [url]http://www.allapi.net/[/url]
    'E-Mail: [email]KPDTeam@Allapi.net[/email]
    Dim lngRes As Long, strPath As String
    'Create a buffer
    strPath = String$(165, 0)
    'retrieve the short pathname
    lngRes = GetShortPathName(strFileName, strPath, 164)
    'remove all unnecessary chr$(0)'s
    GetShortPath = Left$(strPath, lngRes)
End Function

Public Function GetLongPath(ByVal strFileName As String) As String
    Dim lngRes As Long, strPath As String
    'Create a buffer
    strPath = String$(165, 0)
    'retrieve the long pathname
    lngRes = GetLongPathName(strFileName, strPath, 164)
    'remove all unnecessary chr$(0)'s
    GetLongPath = Left$(strPath, lngRes)
End Function

Private Sub Test()
    shortpath = GetShortPath("C:/Documents And Settings")

    Longpath = GetLongPath(shortpath)
End Sub
于 2012-07-11T22:00:31.223 回答
1

要使用 vb6/vba 中的 W 函数,您需要声明所有字符串参数:

Private Declare Function GetLongPathName Lib "kernel32" Alias "GetLongPathNameW" _
  (ByVal lpszShortPath As Long, _
   ByVal lpszLongPath As Long, _
   ByVal cchBuffer As Long) As Long

并通过StrPtr(a_string)而不是仅仅a_string.

所以如果你有:

dim s_path as string
dim l_path as string

s_path = "C:\DOCUME~1"
l_path = string$(1024, vbnullchar)

GetLongPathNameA s_path, l_path, len(l_path)

它会变成

dim s_path as string
dim l_path as string

s_path = "C:\DOCUME~1"
l_path = string$(1024, vbnullchar)

GetLongPathNameW strptr(s_path), strptr(l_path), len(l_path)
于 2012-07-11T22:18:59.523 回答