Monday, June 16, 2008

.NET Tip - Get the filename, not the path

One of the problems with using the OpenFileDialog class is that the FileName property always returns the full path name of the file:

OpenFileDialog openFileDialog1 = new OpenFileDialog()
{
Filter = "Text files (*.jpg)*.jpg"
};

Console.WriteLine(openFileDialog1.FileName); //---e.g. C:\Windows\text.txt---

To retrieve only the filename and not the path, feed it to the FileInfo class, like this:

FileInfo fi = new FileInfo(openFileDialog1.FileName);
Console.WriteLine(fi.Name); //---text.txt---
Console.WriteLine(fi.Directory); //---C:\Windows---

Cool, isn't it?

No comments: