获取Unicode文件名的完整路径

时间:2012-07-09 04:25:37

标签: vba unicode path

我有一个短版本或DOS格式的路径(“C:/ DOCUME~1”例如)并希望得到它的完整路径/长路径(“C :/ Documents And Settings“ eg。)。

我试过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,但似乎什么都不做,因为BOTH Unicode和非Unicode文件名,总是返回0.在MSDN中,只有关于C / C ++的GetLongPathNameW的文章,而不是VB / VBA的文章。我可以做错事吗?

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

此致

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

要使用vb6 / vba中的W函数,请将所有字符串参数声明为long:

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)