How to get the file only?

How to get the file name only from the full file path?

MY path -  C:\Documents and Settings\Arshad\My Documents\ravi.txt
+3
source share
4 answers

Look at this: Get a file name without a path or extension .

Here is the function from the link provided:

Public Function GetFileName(flname As String) As String

    'Get the filename without the path or extension.
    'Input Values:
    '   flname - path and filename of file.
    'Return Value:
    '   GetFileName - name of file without the extension.

    Dim posn As Integer, i As Integer
    Dim fName As String

    posn = 0
    'find the position of the last "\" character in filename
    For i = 1 To Len(flname)
        If (Mid(flname, i, 1) = "\") Then posn = i
    Next i

    'get filename without path
    fName = Right(flname, Len(flname) - posn)

    'get filename without extension
    posn = InStr(fName, ".")
        If posn <> 0 Then
            fName = Left(fName, posn - 1)
        End If
    GetFileName = fName
End Function

When entering

C:\Documents and Settings\Arshad\My Documents\ravi.txt

this function returns

ravi

The function is called as such:

Dim FileName As String
FileName = GetFileName("C:\Documents and Settings\Arshad\My Documents\ravi.txt")
+4
source

This is the shortest way:

Public Function GetFileName(FilePath As String) As String
   Dim l() as string
   l=split(FilePath,"\")
   GetFileName=l(UBound(l))
End Function

Tell me if you can find a shorter code;)

+3
source

-

Here is the best and short way.

Return file name from FullPath

' ** C:\Windows\System32\calc.exe > Ret: calc.exe
Private Function GetFilenameFromPath(FullPath As String) As String
   GetFilenameFromPath = Right(FullPath, Len(FullPath) - InStrRev(FullPath, "\"))
End Function

Return Path from FullPath

' C:\Windows\System32\calc.exe > Ret: C:\Windows\System32\
Private Function GetDirectoryFromPath(FullPath As String) As String
   GetDirectoryFromPath = Left(FullPath, InStrRev(FullPath, "\"))
End Function
0
source

Source: https://habr.com/ru/post/1717328/


All Articles