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
atomicgs12Asked:
Who is Participating?
 
Patrick MatthewsCommented:
atomicgs12,

You included the VB Classic zone, so here is a VB6 / VBA / VBScript approach:


DirPath = Left(strPath, InStrRev(strPath, "\\") - 1)

Open in new window



Patrick
0
 
jppintoCommented:
Dim fullPathFileName As String = "c:\docs\folder1\test.txt "
MsgBox(My.Computer.FileSystem.GetParentPath(fullPathFileName))

jppinto
0
 
jppintoCommented:
Dim fullPathFileName As String = "c:\docs\folder1\test.txt "
Dim fi As New System.IO.FileInfo(fullPathFileName)
MsgBox(fi.DirectoryName)
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
atomicgs12Author Commented:
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
0
 
wdosanjosCommented:
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

0
 
CodeCruiserCommented:
>That is ultimately what I am doing, checking if the directory exists.

Use IO.File.Exists and IO.Directory.Exists functions
0
 
atomicgs12Author Commented:
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
0
 
VBClassicGuyCommented:
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
0
 
VBClassicGuyCommented:
Opps, typed too slow. Sorry.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.