Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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...

Posted

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.

"Never ascribe to malice that which can adequately be explained by incompetence." -- Napolean Bonaparte
  • Leaders
Posted

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"

[sIGPIC]e[/sIGPIC]
Posted

Thanks for the suggestions. I ended up using the following:

 

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

 

this seems to do the trick...

Posted
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.
Posted
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.
"Never ascribe to malice that which can adequately be explained by incompetence." -- Napolean Bonaparte
  • *Experts*
Posted

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

"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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...