C# : Parsing information out of a path

Posted by mbcrump on Geeks with Blogs See other posts from Geeks with Blogs or by mbcrump
Published on Tue, 20 Apr 2010 14:44:19 GMT Indexed on 2010/04/20 21:54 UTC
Read the original article Hit count: 204

Filed under:

If you have a path for example: \\MyServer\MyFolderA\MyFolderB\MyFile.jpg and you need to parse out the filename, directory name or the directory parent name. You should use the fileinfo class instead of a regex expression or a string split. See the example code below:

 

Code Snippet
  1. using System;
  2. using System.IO;
  3.  
  4. class Test
  5. {
  6.     static void Main(string[] args)
  7.     {
  8.         string file = @"\\MyServer\MyFolderA\MyFolderB\MyFile.jpg";
  9.         FileInfo fi = new FileInfo(file);
  10.         Console.WriteLine(fi.Name);                  // Prints File.jpg
  11.         Console.WriteLine(fi.Directory.Name);        // Prints FolderB
  12.         Console.WriteLine(fi.Directory.Parent.Name); // Prints FolderA
  13.     }
  14. }

© Geeks with Blogs or respective owner