Link to home
Start Free TrialLog in
Avatar of atomicgs12
atomicgs12Flag for United States of America

asked on

Extract path from string in Visual Basic

I have a full path passed as say: c:\docs\folder1\test.txt in a string variable as say:
Dim strPath As String = "c:\\docs\\folder1\\test.txt"
I want to extract the directory path without the folder name, so the result would be:
strPath = "c:\\docs\\folder". Of course the folder can be of any name so I DO NOT want to search just for "test.txt".

An example would be nice.

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Patrick Matthews
Patrick Matthews
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Dim fullPathFileName As String = "c:\docs\folder1\test.txt "
MsgBox(My.Computer.FileSystem.GetParentPath(fullPathFileName))

jppinto
Dim fullPathFileName As String = "c:\docs\folder1\test.txt "
Dim fi As New System.IO.FileInfo(fullPathFileName)
MsgBox(fi.DirectoryName)
Avatar of atomicgs12

ASKER

jppinto -

for Dim fi As New System.IO.FileInfo(fullPathFileName), what happens if c:\docs\folder1 does not exist? That is ultimately what I am doing, checking if the directory exists.

Thanks
Try the following.  The file or directory are not required to exist.

Dim dirname As String = System.IO.Path.GetDirectoryName("c:\docs\folder1\test.txt")

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just so we are all on the same page, I want to test if the directory exists, without the file name on the end. My logis is, test if directory exists, if not do nothing, if directory does exists, test for file name if file name exists add to file, if file does not exist and directory DOES exists create new file then add data.

Thanks
I'll dispense wit the DIM's, I'm sure you know them...

FullPath = "c:\\docs\\folder\\test.txt"
i = InStrRev(FullPath, "\\")
If i Then
   PathName = Left(FullPath, i - 1)
   FileName = Mid(FullPath, i + 2)
   If Len(Dir(PathName)) Then
      If Len(Dir(FullPath)) Then
        '' CODE HERE TO ADD TO FILE
      Elae
         h = FreeFile
         Open FullPath For Output As #h
         Close #h
         '' CODE HERE TO ADD TO FILE
      End If
End If
Opps, typed too slow. Sorry.