Tuesday, December 16, 2008

The Joys of the Path Class

I'm beginning to think that the Path class is sadly one of the most overlooked classes out there. I've seen plenty of good developers coming up with all sorts of crazy string parsing code to split apart filenames, when the Path class is quietly sitting alone, with no friends. Because I want the Path class to be social and have as many friends as its brothers, FileInfo and DirectoryInfo, allow me to introduce you to a few of the Path class's methods:
  • Path.GetDirectoryName - Takes a string parameter, and returns a string representing only the directory name of the file. Say goodbye to filename.Substring(0, filename.LastIndexOf(@"\")), and say hello to this method.
  • Path.GetFileName - How many of you have found yourself typing string filename = path.Substring(filename.LastIndexOf(@"\") + 1); when you could have just been using this method, which nicely extracts the filename out of the whole path for you?
  • Path.GetFileNameWithoutExtension - Oh, this is a nice one. If given the string "C:\Program Files\CompanyName\Filename.txt", Path.GetFileNameWithoutExtension will return simply "Filename".
  • Path.GetTempPath - Returns a string containing the full path to the system's temporary folder.
  • Path.ChangeExtension - Will change the extension of any filename in a path, and return to you the new full path.
  • Path.Combine - One of my favorites, this will allow me to take a string like "C:\Program Files\CompanyName" and another string like "Filename.txt", and easy get "C:\Program Files\CompanyName\Filename.txt".

Again, this is sadly overlooked by many developers, but it's there, so use it when you need to.