Visual Basic > Files Directories Drives
How to parse the path, file name and extension from a string.
How to parse the path, file name and extension from a string. ' This function will return just the path name from a ' string containing a path and file name. Function ParsePath (sPathIn As String) As String Dim I As Integer For I = Len(sPathIn) To 1 Step -1 If InStr(":\", Mid$(sPathIn, I, 1)) Then Exit For Next ParsePath = Left$(sPathIn, I) End Function ' This function will return just the file name from a ' string containing a path and file name. Function ParseFileName (sFileIn As String) As String Dim I As Integer For I = Len(sFileIn) To 1 Step -1 If InStr("\", Mid$(sFileIn, I, 1)) Then Exit For Next ParseFileName = Mid$(sFileIn, I + 1, Len(sFileIn) - I) End Function ' This function will return the file extension from a ' string containing a path and file name. Function GetFileExt (sFileName As String) As String Dim P As Integer For P = Len(sFileName) To 1 Step -1 'Find the last ocurrence of "." in the string If InStr(".", Mid$(sFileName, P, 1)) Then Exit For Next GetFileExt = Right$(sFileName, Len(sFileName) - P) End Function ' Example: ' Add a Textbox (Text1), add command button (Command1) and ' add 3 labels (Label1, 2, 3) ' Add this code to the Command1 click event: Sub Command1_Click () Dim sTargetString As String ' Store the string sTargetString = Text1.Text 'Display the path Label1 = ParsePath(sTargetString) 'Display the filename Label2 = ParseFileName(sTargetString) 'Display the file's extension Label3 = GetFileExt(sTargetString) End Sub ' Run the program and type a valid path and file name in the Text1 ' textbox and click the Command1 button.
Visual Basic Codes
ActiveX
Miscellaneous
Applications
Code Snippets
Common Dialogs
Special Effects
Database Stuff
Date Time
Files Drives
Forms
Graphics Games
Internet Stuff
Multimedia
Other
Strings
Windows