Joey Joey - 1 month ago 9
Vb.net Question

How do I open a folder using the filename directory?

I have a

ListBox
which contains directories and file names which would be shown like this
C:\File.txt
. I would like to open the folder of the selected item using a
ContextMenuStrip
which would be like this

If System.IO.File.Exists(ListBox1.SelectedItem) = True Then
Process.Start(ListBox1.SelectedItem)
End If


but of course that only opens the file instead of the folder, how would I trim off the filename so it would only open the folder?

Note:
Process.Start("C:\")
wouldn't be a solution for me as there would be many different directories/files within this
ListBox
, so it wouldn't always be the same folder for all the listed files.

Answer

Use the System.IO.Path.GetDirectoryName() method. This returns the folder path.

For example:

Dim filePath As String = "C:\something\file.txt"
Dim folderPath As String = Path.GetDirectoryName(filePath)

Returns C:\something. So modify your code to:

If System.IO.File.Exists(ListBox1.SelectedItem) = True Then
    Process.Start(Path.GetDirectoryName(ListBox1.SelectedItem))
End If