Getting the filename from a path string - System.IO.Path to the rescue

I was looking for something simple to get the file name for the selected file of an OpenFileDialog in C# today.  Of course you can parse the string looking for backslash, etc. It annoyed me that there was no FileText property or something similar which returns this little nugget.

After a short Google search, I found that the System.IO namespace contains Path.GetFileName.  This helpful little static method returns the filename given a path (Path.GetFileName(string path);)   (supported in 1.x, 2.0, 3.0).  If you dig a little deeper, you will see that the Path class has a nice collection of helper methods for getting information about a file, its path, and its directory.  If you reflect on the function, you see that it simply does the parsing for you.

I am sure that every .Net developer already knows this, but its funny how it did not come up very easily when I did my search.

This article is part of the GWB Archives. Original Author: Scott Lock

New on Geeks with Blogs