Directory.GetParent and slashes
Running this snippet
var path1 = @"C:\Temp\SomeFolder"; var path2 = @"C:\Temp\SomeFolder\"; Console.WriteLine(Directory.GetParent(path1)); Console.WriteLine(Directory.GetParent(path2));
Same story with Path.GetDirectoryName(), which also can be used to obtain parent folder, but will similarly fail in case of \ at the end.
I do really like Path.Combine() for ignoring slashes at the end and do really hate some guys who make some methods returning path with slash (referring to AppDomain.CurrentDomain.BaseDirectory *angryface*).
Question: how to properly handle possible slash at the end of given path when I need to get one of the parent directories?
Here is another snippet
var path1 = @"C:\Temp\SomeFolder"; var path2 = @"C:\Temp\SomeFolder\"; var dir1 = @"Test"; var dir2 = @"Test\"; Console.WriteLine(Path.Combine(path1, dir1)); Console.WriteLine(Path.Combine(path1, dir2)); Console.WriteLine(Path.Combine(path2, dir1)); Console.WriteLine(Path.Combine(path2, dir2));
Path.Combine works properly (ignoring ending slash of the first path, or well, adding it when it's missing), while persisting ending slash of second path (for whatever reasons, I do not care, because using resulting path in more Path.Combines will works as well).
As I understand Test and Test\ pointing at the same folder in directory structure. And if I want to get parent (previous folder), then Directory.GetParent should return me previous folder, and not Test folder again.
Question: how to properly handle possible slash at the end of given path when I need get one of the parent directories?
Just trim it from the input string. Use TrimEnd:
However returning the complete path when the string is terminated by \ is desired behaviour
However, passing "C:\Directory\SubDirectory\" returns "C:\Directory\SubDirectory", because the ending directory separator is after "SubDirectory".