Backwards traverse of a path in C# -- Directory.GetParent()
Editimage credit |
I encountered many time when writing an C# .Net MVC application, I need to access the file structure in the server. I used to get the current running path by
AppDomain.CurrentDomain.BaseDirectoryThen do string manipulation to get to the root that I need and then use the Path class to create the file path I need.
Yet today I discovered the method
Directory.GetParent(path);Which seems save my time to do the string manipulation to get the parent directory! You can see the smaple code below
void GetParent(string path) { try { System.IO.DirectoryInfo directoryInfo = System.IO.Directory.GetParent(path); System.Console.WriteLine(directoryInfo.FullName); } catch (ArgumentNullException) { System.Console.WriteLine("Path is a null reference."); } catch (ArgumentException) { System.Console.WriteLine("Path is an empty string, " + "contains only white spaces, or " + "contains invalid characters."); } }
Further reading : Directory.GetParent Method (System.IO)
Backwards traverse of a path in C# -- Directory.GetParent()
Reviewed by DF
on
8:25:00 PM
Rating: