nbrege Posted January 24, 2006 Posted January 24, 2006 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... Quote
VagabondSW Posted January 24, 2006 Posted January 24, 2006 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. Dim filename As String = "release notes 0.9a beta.html" We only want to strip off the file extension. Dim newString As String newString = filename.Substring(0, filename.LastIndexOf(".") + 1) That should get you where you want to go. Quote "Never ascribe to malice that which can adequately be explained by incompetence." -- Napolean Bonaparte
Leaders snarfblam Posted January 24, 2006 Leaders Posted January 24, 2006 The static Sytem.IO.Path class is good for elementary filename/path manipulation System.Windows.Forms.MessageBox.Show( _ System.IO.Path.GetFileNameWithoutExtension("C:\\Filename.txt")) ' Displays "Filename" Quote [sIGPIC]e[/sIGPIC]
nbrege Posted January 25, 2006 Author Posted January 25, 2006 Thanks for the suggestions. I ended up using the following: filetmp = Microsoft.VisualBasic.Left(filename, InStrRev(filename, ".") - 1) this seems to do the trick... Quote
mskeel Posted January 25, 2006 Posted January 25, 2006 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. Quote
VagabondSW Posted January 25, 2006 Posted January 25, 2006 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. Quote "Never ascribe to malice that which can adequately be explained by incompetence." -- Napolean Bonaparte
*Experts* Nerseus Posted January 25, 2006 *Experts* Posted January 25, 2006 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 Quote "I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.