Dr. Atul Tiwari
Dr. Atul Tiwari

Reputation: 1085

How to get folder path of file opened from OpenFileDialog in Visual Basic 2013

I am opening a file using OpenFileDialog. My code is as follows -

Public Sub ShowOpenDialog()
Dim f As New OpenFileDialog
f.InitialDirectory = GetFolderPath(SpecialFolder.MyDocuments)
f.Title = "Open File"
f.CheckFileExists = True
f.CheckPathExists = True
f.DefaultExt = "*.txt"
f.Filter = "Text (*.txt)|*.txt|All Files|*.*"
f.FilterIndex = 1
f.RestoreDirectory = True
If f.ShowDialog() = DialogResult.OK Then
'f.FileName displays file path, what I need is its folder path
'Performing action with f.FileName
End If
End Sub

I also need file's location (folder path), but I couldn't find, how to get it?

p.s. - I (also) need to open the file, so I have to use OpenFileDialog instead of FolderBrowserDialog. That's why, I am searching for a way to get file's Folder Path from OpenFileDialog

Upvotes: 1

Views: 10738

Answers (1)

David
David

Reputation: 91

This returns the parent folder name. (Works for Files and Folders (Folders, which do not end with "\"))

    ''Be sure to   Import Imports System.IO
Function GetDirPath(ByVal file As String) As String
    Dim fi As New FileInfo(file)
    Return fi.Directory.ToString
End Function

Upvotes: 4

Related Questions