System.IO.DirectoryInfo可能是完成您所要求的最干净的方法。
var path = "\\\\ServerName\\Documents\\MasterDocumentFolder\\";
string newPath = new DirectoryInfo(path).Parent.CreateSubdirectory("NewDocumentFolder1").FullName;
Console.WriteLine(newPath.FullName);
//> "\\ServerName\Documents\NewDocumentFolder1\"
请注意, DirectoryInfo 不需要现有的或可访问的目录:
var dir = new DirectoryInfo(@"C:\Asdf\Qwer\Zxcv\Poiu\Lkj\Mn");
Console.WriteLine( dir.Exists );
//> False
但是确保它的存在是一件轻而易举的事
var dir = new DirectoryInfo(@"C:\Asdf\Qwer\Zxcv\Poiu\Lkj\Mn");
dir.Create();
Console.WriteLine( dir.Exists );
//> True
它还会做一些漂亮的事情,比如解析相对路径:
var dir = new DirectoryInfo(@"C:\Asdf\Qwer\Zxcv\Poiu\Lkj\..\..\..\Mn");
Console.WriteLine( dir.FullName );
//> C:\Asdf\Qwer\Mn
关于修剪和附加斜杠的其他答案,请注意 Directory.GetParent("...\") 和 DirectoryInfo("...\").Parent 在处理尾随 \'s 时的行为差异 - DirectoryInfo 更加一致:
Console.WriteLine( Directory.GetParent( @"C:\Temp\Test" ).FullName );
//> C:\Temp
Console.WriteLine( Directory.GetParent( @"C:\Temp\Test\" ).FullName );
//> C:\Temp\Test
Console.WriteLine( new DirectoryInfo( @"C:\Temp\Test" ).Parent.FullName );
//> C:\Temp
Console.WriteLine( new DirectoryInfo( @"C:\Temp\Test\" ).Parent.FullName );
//> C:\Temp
同样,为避免处理尾部斜杠,请始终使用 Path.Combine() 连接路径和文件名。无论路径是否包含尾随\,它都会正确处理路径:
Console.WriteLine( Path.Combine( @"C:\Temp\Test\", "Test.txt" ) );
//> C:\Temp\Test\Test.txt
Console.WriteLine( Path.Combine( @"C:\Temp\Test", "Test.txt" ) );
//> C:\Temp\Test\Test.txt
Console.WriteLine( Path.Combine( @"C:\", "Temp", "Test", "Test.txt" ) );
//> C:\Temp\Test\Test.txt