Reputation: 123
This is probably a simple question, I'm writing a WinForms C# application in VS 2012. I was wondering if there a way to add an extension such as .csv to some writing in a textbox. Say the user wrote in C:\Users\Desktop\filename but left out the .csv part of the path. Is there any way to add the .csv after an execute button is clicked?
Any help would be much appreciated.
Upvotes: 1
Views: 388
Reputation: 32681
If you do not want to change a valid extension in the string, you could do it like this instead:
// first test for an extension
if(!Path.HasExtension(textBox1.Text.Trim()))
{
// then add on '.csv' if one does not exist
string path = Path.ChangeExtension(textBox1.Text.Trim(), ".csv");
// ... use path ...
}
Upvotes: 1
Reputation: 64078
You can use Path.ChangeExtension
.
// Nota bene: Path.ChangeExtension does not change textBox1.Text directly (or any
// argument given), you MUST use the result if you care about it.
string newPath = Path.ChangeExtension(textBox1.Text, "csv");
The period is optional, and the filename component need not include an extension.
As a future reference, if you can think of something you need to do with a path to a file or a directory...it exists in System.IO.Path
. Rare for there not to be support for a common task in that class.
Upvotes: 9