String question

nbrege

Freshman
Joined
Jan 12, 2006
Messages
34
What's the best way to strip an extension from a filename?
If I have the string MyString = "MyFile.txt" , how can I get just "MyFile"?
I know this is an easy one, but I'm fairly new to VB. Thanks...
 
It is simple to do, but not necessarily simplistic. What I mean is the straight-forward methods that immediately pop to mind (Split on ".", Remove last three characters) don't work for all files. For example:

"release notes 0.9a beta.html"

So, we start with a String.
Visual Basic:
Dim filename As String = "release notes 0.9a beta.html"

We only want to strip off the file extension.
Visual Basic:
Dim newString As String
newString = filename.Substring(0, filename.LastIndexOf(".") + 1)

That should get you where you want to go.
 
The static Sytem.IO.Path class is good for elementary filename/path manipulation
Visual Basic:
System.Windows.Forms.MessageBox.Show( _
	System.IO.Path.GetFileNameWithoutExtension("C:\\Filename.txt"))
' Displays "Filename"
 
Thanks for the suggestions. I ended up using the following:

Visual Basic:
filetmp = Microsoft.VisualBasic.Left(filename, InStrRev(filename, ".") - 1)

this seems to do the trick...
 
Rather than using the "native" Visual Basic method, it's better (at least I think so) to use the general classes from the .Net framework. Marble's suggestion is, in my opinion, the better solution.
 
My suggestion is better than the VisualBasic helper functions (i.e. Left and InStr), but Marble's solution is the best one on the board so far.
 
I wouldn't use Left without checking if InStrRev returned 0. If you pass it a filename like "MyText" then your code will throw an exception. I'd use Marble's suggestion.

-ner
 
Back
Top