C# : Parsing information out of a path
- by mbcrump
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 using System; using System.IO; class Test { static void Main(string[] args) { string file = @"\\MyServer\MyFolderA\MyFolderB\MyFile.jpg"; FileInfo fi = new FileInfo(file); Console.WriteLine(fi.Name); // Prints File.jpg Console.WriteLine(fi.Directory.Name); // Prints FolderB Console.WriteLine(fi.Directory.Parent.Name); // Prints FolderA } }