Récupérer un chemin de fichier au format Short (même si ce fichier n'existe pas)


Contenu du snippet

Private Declare Function DeleteFile Lib "kernel32" Alias "DeleteFileA" (ByVal lpFileName As String) As Long
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 MakeSureDirectoryPathExists Lib  "imagehlp.dll" (ByVal lpPath As String) As Long
'
Function GetShortPath(ByVal sFile As String, Optional bCreate As Boolean = False)  As String
    If bCreate Then
        Call MakeSureDirectoryPathExists(Left$(sFile, InStrRev(sFile, "\")))
        Dim FF As Integer: FF = FreeFile
        Open sFile For Output As #FF
            Print #FF, vbNullString
        Close #FF
        DoEvents
    End If
    
    Dim lRet As Long
    GetShortPath = String(1024, Chr$(0))
    lRet = GetShortPathName(sFile, GetShortPath, Len(GetShortPath))
    GetShortPath = Left$(GetShortPath, lRet)
    
    If bCreate Then Call DeleteFile(sFile)
End Function
'
' ========
' EXEMPLE
' ========
'
MsgBox Environ$("PROGRAMFILES") & "\outlook express\un fichier au hasard.txt" & vbCrLf & _
        GetShortPath(Environ$("PROGRAMFILES") & "\outlook express\un fichier  au  hasard.txt", True)


Compatibilité : VB6, VBA

Disponible dans d'autres langages :

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.