How might I remove the extension off of a file string such as "c:\windows\file.txt.bak" so it becomes just "c:\windows\file.txt"? Thanks.
Printable View
How might I remove the extension off of a file string such as "c:\windows\file.txt.bak" so it becomes just "c:\windows\file.txt"? Thanks.
You can use this code
Code:Function GetFileNameWithoutExtension(ByVal FileName As String) As String
Dim FileN As String
Dim TabFile() As String
Dim i As Integer
TabFile = Split(FileName, ".")
FileN = ""
For i = 0 To UBound(TabFile) - 1
If FileN <> "" Then FileN = FileN & "."
FileN = FileN & TabFile(i)
Next i
GetFileNameWithoutExtension = FileN
End Function
Thanks! Nice code, you make it look easy... :D Then again, it probably is for you... ;)
KWell's code is vb6 only and a file without a suffix returns an empty string.
here's my version:
Code:Public Function DropFileSuffix(ByVal FileName As String) As String
Dim Counter As Long
If InStr(FileName, ".") = 0 Then
' Empty string or no suffix - return the input string
DropFileSuffix = FileName
Else
' Remove the suffix
Counter = Len(FileName)
While Counter > 0 And Mid(FileName, Counter, 1) <> "."
Counter = Counter - 1
Wend
DropFileSuffix = Left(FileName, Counter - 1)
End If
End Function
Is his code VB6 only, because it uses the Split function?
oetje, yes
You can code a split function for vb5 but that's just getting too complicated for this function.
take a peek at:Code:Public Function Split(ByVal sIn As String, Optional sDelim As _
String, Optional nLimit As Long = -1, Optional bCompare As _
VbCompareMethod = vbBinaryCompare) As Variant
Dim sRead As String, sOut() As String, nC As Integer
If sDelim = "" Then
Split = sIn
End If
sRead = ReadUntil(sIn, sDelim, bCompare)
Do
ReDim Preserve sOut(nC)
sOut(nC) = sRead
nC = nC + 1
If nLimit <> -1 And nC >= nLimit Then Exit Do
sRead = ReadUntil(sIn, sDelim)
Loop While sRead <> ""
ReDim Preserve sOut(nC)
sOut(nC) = sIn
Split = sOut
End Function
http://support.microsoft.com/support.../Q188/0/07.ASP
Sorry Mark Sreeves for the error and thank a lot for the correction
You could have something easy like this so you don't need the split function or anything:
Code:Function Extension(ByVal strFilename As String) As String
Dim intPos As Integer
Extension = vbNullString
intPos = Len(strFilename)
Do While intPos > 0
Select Case Mid$(strFilename, intPos, 1)
Case "."
Extension = Mid$(strFilename, intPos + 1)
Exit Do
Case Else
End Select
intPos = intPos - 1
Loop
End Function
An example using the StrReverse Function
Reverse the string and look for the first occurence of a "."
Function RemoveExtension(ByVal strFile as String) As String
Dim i As Integer
strFile = StrReverse(strFile)
i = InStr(strText, ".")
If i > 0 Then strFile = Mid$(strFile, i + 1)
strFile = StrReverse(strFile)
RemoveExtension = strFile
End Function