Reputation: 139
I have the below code that obtains a list of txt files from a folder, I would like to remove the .txt from the returned file name, how may I achieve this?
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "Notes"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "TXT" Then
document.write objFile.name & "<br>"
End If
Next
Upvotes: 2
Views: 3263
Reputation: 1
In VBScript, FileSystemObject
has a method for extracting only the file name, called GetBaseName
. There is also a method for extracting only the file extension called GetExtensionName
.
Function GetIT(filespec)
Dim fso, GetTheBase, GetTheExtension
Set fso = CreateObject("Scripting.FileSystemObject")
GetTheBase = fso.GetBaseName(filespec)
GetTheExtension = fso.GetExtensionName(filespec)
End Function
Upvotes: 0
Reputation: 21
Or if you prefer to use a function that processes a string, I coded this for my own site once. This function returns the filename without extension, provided there is a "." anywhere in the filename, of course. If not, it simply returns the input filename.
Function RemoveFileExtension(inputFileName)
IF NOT inStr(inputFileName, ".") > 0 THEN
' Period not found
strReturnvalue = inputFileName
ELSE
' Period found. Locate last
intPositionRight = 1
DO WHILE NOT inStr(right(inputFileName, intPositionRight), ".") > 0
intPositionRight = intPositionRight + 1
LOOP
strReturnvalue = left(inputFileName, len(inputFileName) - intPositionRight)
END IF
RemoveFileExtension = strReturnvalue
End Function
Then you can simply use the function, e.g. like this:
For Each objFile in colFiles
response.write RemoveFileExtension(objFile.name) & "<br>"
Next
Happy coding. :)
Upvotes: 0
Reputation: 53690
This will work:
...
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "TXT" Then
document.write Left(objFile.name, Len(objFile.name)-4) & "<br>"
End If
Next
According to the docs, Left()
Returns a specified number of characters from the left side of a string.
You just need to know how many characters to return. Since you already know that the filename ends in .txt
, you can return all but the last 4 characters. Len(objFile.name)
will give you the full length, and you can subtract from there.
Upvotes: 3