VB使用API时被忽视的字符串数返回问题

  勇芳 2017-2-17 6640

用例题说明

Private Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" (ByVal lpszLongPath As String, ByVal lpszShortPath As String, ByVal cchBuffer As Long) As Long
Public Function 短文件名(LongPath As String) As String
    Dim ShortPath As String
    Const MAX_PATH = 260
    Dim ret&
    ShortPath = Space$(MAX_PATH)
    ret& = GetShortPathName(LongPath, ShortPath, MAX_PATH)
    If ret& Then
        短文件名 = Left$(ShortPath, ret&)
    End If
End Function

这是我多年前网上找的,一直在用,不管如何看代码,没任何问题,但实际上有问题。

当遇到有中文时,GetShortPathName 返回的字符数量就不对了。

因为中文为2个,而VB处理当成1个,就有问题了。

所以,我们必须这样做避免出问题

    If ret& Then
        ret& = InStr(ShortPath, Chr(0)) - 1
        短文件名 = Left$(ShortPath, ret&)
    End If

API有很多类似这个,返回字符串数的,都要注意,不然BUG更本找不到。


以上是将长文件名(带路径)转换为短文件名。

因国家互联网安全管理要求,关闭回帖功能。大家需要留言,请使用【勇芳软件客服】即时联系勇芳点此打开->>勇芳软件客服
返回
联系勇芳
发新帖 搜索 反馈 回顶部