C#: Need to remove last folder from file name path

What you are looking for is the GetParent() method in the Directory class

string path = @"C:\Documents\MasterDocumentFolder\";
DirectoryInfo parentDir = Directory.GetParent(path);
// or possibly
DirectoryInfo parentDir = Directory.GetParent(path.EndsWith("\\") ? path : string.Concat(path, "\\"));

// The result is available here
var myParentDir = parentDir.Parent.FullName

Thats ugly, but works

string path = @"C:\Documents\MasterDocumentFolder\file.any";
var lastFolder = Path.GetDirectoryName(path);
var pathWithoutLastFolder = Path.GetDirectoryName(lastFolder);

But if you have less than one level of directories (drive root), then pathWithoutLastFolder will be null, so you have to deal with it.

Tags:

C#