Search Tools Links Login

Path manipulation

There are many methods you can use to return certain parts of a fully qualified path to a file. Here is the SHORTEST and FASTEST way to 1) return just the path, 2) return just the filename, and 3) change the extension of a filename. The code is so short that it is probably faster to keep it inline than to create additional functions. (I've done so here to better illustrate the parameters.

Original Author: Chris Wilson


I've intentionally left out doing any checks for a valid path in order to show the simplicity of the code.


Public Sub PathTest
' Return just the path "c: est"
' TRUE strips the backslash, FALSE retains it
Debug.Print JustPath("c: estmyfile.txt", "", True)
' Return just the filename "myfile.txt"
' Change "" to "/" to handle UNIX or URL pathnames!
Debug.Print JustFile("c: estmyfile.txt", "")
' Change the extension to "bak" and return "c: estmyfile.bak"
Debug.Print ChangeExt("c: estmyfile.txt", "bak")
' Change the extension and return just the filename "myfile.bak"
' Change "" to "/" to handle UNIX or URL pathnames!
Debug.Print JustFile(ChangeExt("c: estmyfile.txt", "bak"), "")
End Sub
Public Function JustPath(ByVal filepath As String, ByVal dirchar As String, ByVal stripbs As Integer) As String
' Returns just the path
' TRUE evaluates to -1, FALSE evaluates to 0 so
' simple addition is all we need at the end to remove the slash
JustPath = Mid$(filepath, 1, InStrRev(filepath, dirchar) + stripbs)
End Function
Public Function JustFile(ByVal filepath As String, ByVal dirchar As String) As String
' Returns just the filename
JustFile = Mid$(filepath, InStrRev(filepath, dirchar) + 1)
End Function
Public Function ChangeExt(ByVal filepath As String, ByVal newext As String) As String
' Changes the extension
ChangeExt = Mid$(filepath, 1, InStrRev(filepath, ".")) & newext
End Function

About this post

Posted: 2002-06-01
By: ArchiveBot
Viewed: 97 times


Visual Basic 6


No attachments for this post

Loading Comments ...


No comments have been added for this post.

You must be logged in to make a comment.