Extract and get/retrieve the Filename only from a path using VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)
 

One Way to do It


'
'This will extract and return the filename from the specified path and filename.
'
Dim filePath As String = "c:\MyDirectory\MYFile.txt"
Dim slashPosition As Integer = filePath.LastIndexOf("\")
Dim filenameOnly As String = filePAth.Substring(slashPosition + 1)

MsgBox(filenameOnly)

 

Second Way to do It. The better way actually.

'
'Thanks to Jim for this code as it is actually a easier way than the original code I
'posted. Just remember that this code will INCLUDE the extension. So you will need to
'add code to remove it if you don't want the files extension.
Dim fullPath As String = "c:\MyDirectory\MYFile.txt"
Dim dirName As String = IO.Path.GetFileName(fullPath)

    MsgBox(dirName)

 

12 thoughts on “Extract and get/retrieve the Filename only from a path using VB.NET

  1. Jim

    How about using the IO object

    Dim fullPath As String = “c:\MyDirectory\MYFile.txt”

    Dim dirName As String = IO.Path.GetFileName(fullPath)

    Reply
  2. Babu

    Hi This may help you..

    Dim sFileName as String
    Dim sFolderPath as String
    
    sFolderPath = fdlgOpen.SelectedPath
    sFileName = ASSIGN FULL PATH WITH FILENAME
    sFullPath = txtFolderpath.text
    sFileName = Replace(sFileName,sFolderPath & "\" ,"")
    

    Note: Most of the time you will Select the file using dlg control…

    Reply
  3. Ian W

    Hi, To get the file name without the extension, you can use

    Dim fullPath As String = "c:\MyDirectory\MYFile.txt" 
    Dim dirName As String = IO.Path.GetFileNameWithoutExtension(fullPath) 
    

    Not sure if this is available in all versions of .Net, but definately in 2008 and 2010.

    Ian

    Reply

Leave a Reply

Your email address will not be published.