Directory.GetParent and slashes

Running this snippet

var path1 = @"C:\Temp\SomeFolder";
var path2 = @"C:\Temp\SomeFolder\";




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

Directory.GetParent Method

However, passing "C:\Directory\SubDirectory\" returns "C:\Directory\SubDirectory", because the ending directory separator is after "SubDirectory".

Need Your Help

PHP Namespaces & Referencing Classes not contained within Namespaces


I have a simple question, which should hopefully have a quick answer. The code I have written makes heavy use of namespaces (I use fully qualified names everywhere); however, a piece of code (a cal...

Convert text to XML using XSLT without knowing what the “schema” would be

xml xslt text

I have a text document that I want to convert to XML using XSLT for easier processing.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.