|
Получение длинного и короткого имени файла/директории |
|
|
Данный вопрос очень часто звучит на многих форумах: "Как мне получить короткое имя файла" или "Как мне получить длинное имя файла, зная короткое". Далее следует ответ на эти вопросы.
P.S. Надеюсь, мне не надо объяснять что такое "длинное"/"короткое" имя файла. :)) Private Const MAX_PATH& = 260
Private Const INVALID_HANDLE_VALUE = -1
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Private Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReservedЇ As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type
Private Declare Function apiFindFirstFile Lib "kernel32" Alias
"FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA)
As Long
Private Declare Function apiFindClose Lib "kernel32" Alias "FindClose"
(ByVal hFindFile As Long) As Long
Private Declare Function apiGetShortPathName Lib "kernel32" Alias
"GetShortPathNameA" (ByVal lpszLongPath As String, ByVal lpszShortPath As
String, ByVal cchBuffer As Long) As Long
Function fGetShortName(ByVal stLongPath As String) As String
Dim stShortPath As String
Dim lngBuffer As Long, lngRet As Long
stShortPath = String$(MAX_PATH, 0)
lngBuffer = Len(stShortPath)
lngRet = apiGetShortPathName(stLongPath, stShortPath, lngBuffer)
fGetShortName = Left(stShortPath, lngRet)
End Function
Function fGetLongName(ByVal strFilename As String) As String
Dim lpFindFileData As WIN32_FIND_DATA
Dim strPath As String, lngRet As Long
Dim strFile As String, lngx As Long, lngY As Long
Dim strTmp As String
strTmp = ""
Do While Not lngRet = INVALID_HANDLE_VALUE
lngRet = apiFindFirstFile(strFilename, lpFindFileData)
strFile = Left$(lpFindFileData.cFileName, InStr(lpFindFileData.cFileName, vbNullChar) - 1)
If Len(strFilename) > 2 Then
strTmp = strFile & "\" & strTmp
strFilename = fParseDir(strFilename)
Else
strTmp = strFilename & "\" & strTmp
Exit Do
End If
Loop
fGetLongName = Left$(strTmp, Len(strTmp) - 1)
lngY = apiFindClose(lngRet)
End Function
Private Function fParseDir(strInFile As String) As String
Dim intLen As Long, boolFound As Boolean
Dim i As Integer, F As String, strDir As String
intLen = Len(strInFile)
If intLen > 0 Then
boolFound = False
For i = intLen To 1 Step -1
If Mid$(strInFile, i, 1) = "\" Then
F = Mid$(strInFile, i + 1)
strDir = Left$(strInFile, i - 1)
boolFound = True
Exit For
End If
Next i
End If
If boolFound Then
fParseDir = strDir
Else
fParseDir = strInFile
End If
End Function
Private Sub Command1_Click()
Dim fShort
fShort = fGetShortName("C:\Program Files")
MsgBox fShort
fShort = fGetLongName(fShort)
MsgBox fShort
End Sub
|
|
|
|
|
|
|