changing file extensions: vb.net

Kaos

[H]ard|Gawd
Joined
Oct 14, 2003
Messages
1,328
Im trying to teach myself vb.net, and the way Im doing this is that anytime I need to do something on my computer and it's not part of windows or some big software package thats out there, I figured I would write a tool to do it.

So i had to renam a whole directory worth of files the other day (actually just prefixing a string to the existing file name, which I was able to do.) Even though that's all I needed it for at the moment, Im trying to expand my learning and make this thing able to change the extension of a file.

This is where im having n00b brain. I know i can't rely on lopping off the last three characters because what if a file has a 4 char extension? I think what I need to do is move over from the right char by char until I encounter the first period, then I can axe everything to the right of it.

Im not looking for the code to do this, id like to do that for myself, but rather what method will be the most effective and flexible?

Thanks for your time.
 
Well there is always the string class methods like LastIndexOf which will give you the last index of the period in the string.

So that way all you would have to do is use substring which in .NET takes two parameters
the starting index which is going to be 0, and the length of characters you want which will be lastIndexOf.

So newFileName = fileName.substring(0,fileName.LastIndexOf("."));
 
thanks, I will definately give that a try today during lunch and post my results.
 
Banko's got the right idea, but you'll find that code falls over on files with no extension.
 
Similar to putting your faith in a loud guitar, trusting MS libraries can be beneficial.

Here are two lines that can help you out quite a bit:

Code:
System.IO.Path.GetFileNameWithoutExtension(path)

Microsoft.VisualBasic.Rename(path, System.IO.Path.GetFileNameWithoutExtension(path) + "your extension")

You can assemble them in your own fashion.
 
Sweet, what i've done rather than put all the code in for the button press, is make a sub that contains what each variation of renaming would do.

I just learned that you can create your own subs today, so that tells you about how long ive been doing this.
 
Back
Top