Home > front end >  How can I separate the File Name from its full path VB .Net
How can I separate the File Name from its full path VB .Net

Time:04-08

I need to separate the name of a file from its full path, in VB Net. I am using open FileDialog to get the file. This is How i am doing

Dim openFileDialog1 As New OpenFileDialog With {
        .InitialDirectory = "c:\\",
        .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*",
        .FilterIndex = 2,
        .RestoreDirectory = True
    }
        If (openFileDialog1.ShowDialog() = DialogResult.OK) Then

        filePath = openFileDialog1.FileName
    End If

With this code i am getting the Full Path along with the File name. For example "C:\mydir\docuemnts\myfile.ext" Now what I want is, I want to separate the full path from the file name i.e. "C:\mydir\docuemnts" like this.

I want to do it something like this in the form of function where i provide the full path along with file name and it return me the path without file name

    Private Shared Function GetSubPathFromString(ByVal fullPath As String) As String
    Dim subpath As String = String.Empty
    ' Logic to Implement this 
    Return subpath
End Function

CodePudding user response:

These are a few of the basic function of System.IO.Path.

'Gets filename with extension
System.IO.Path.GetFileName(filepathandname) 
    
'Gets path up to the filename
System.IO.Path.GetDirectoryName(filepathandname) 

'Gets filename without extention
System.IO.Path.GetFileNameWithoutExtension(filepathandname) 

Full documentation here: https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname?view=net-6.0

CodePudding user response:

dim directory as string = new FileInfo(yourpath).DirectoryName

This Works For me as mentioned in one of the comment Thanks to @andrew

  • Related