Extract path from file path?

techwiz24

Well-known member
Joined
Jun 2, 2010
Messages
51
Programming Experience
Beginner
I have a VB.net application in which I am using a 3rd party .dll to create a file and save it. Currently, it throws exceptions if I try to save it in a non-existing directory. What I'm trying to say is if the user enters a place that it saves to, it checks if it exists and then if it does not exist, asks the user if they would like to create it. Currently, the user supplies information like this:
C:\filepath\non-existant-directory\filename.file
 
The following code is what you want. It retrieves the parent directory of filename.file and creates the parent directory if it does not exist. The code has been tested.

VB.NET:
        Dim parentDir As String
        Dim fi As New FileInfo("C:\filepath\non-existant-directory\filename.file")

        parentDir = fi.Directory.FullName

        If Not Directory.Exists(parentDir) Then
            Directory.CreateDirectory(parentDir)
        End If

Instead of using...

VB.NET:
            Directory.CreateDirectory(parentDir)

...you could also use

VB.NET:
fi.Directory.Create()
 
Back
Top