C#:需要从文件名路径中删除最后一个文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13383643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#: Need to remove last folder from file name path
提问by Mick
I'm pulling a file path from a database to use as a file source. I need to remove the last folder from the source path, so I can then create new folders to use as the destination path.
我正在从数据库中提取文件路径以用作文件源。我需要从源路径中删除最后一个文件夹,以便我可以创建新文件夹以用作目标路径。
Example source file path:
\\\\ServerName\\Documents\\MasterDocumentFolder\\
示例源文件路径:
\\\\ServerName\\Documents\\MasterDocumentFolder\\
I need to remove the last folder from that string and get this:
\\\\ServerName\\Documents\\
我需要从该字符串中删除最后一个文件夹并得到这个:
\\\\ServerName\\Documents\\
So I can create a folder like this:
\\\\ServerName\\Documents\\NewDocumentFolder1\\
所以我可以创建一个这样的文件夹:
\\\\ServerName\\Documents\\NewDocumentFolder1\\
Edit: I have updated my example paths to show why the Path.GetDirectoryName() won't work in this case.
编辑:我已经更新了我的示例路径以显示为什么 Path.GetDirectoryName() 在这种情况下不起作用。
采纳答案by Eric Herlitz
What you are looking for is the GetParent() method in the Directory class
你要找的是 Directory 类中的 GetParent() 方法
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
回答by Sergey Berezovskiy
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 pathWithoutLastFolderwill be null, so you have to deal with it.
但是如果您的目录少于一级(驱动器根目录),那么pathWithoutLastFolder将会是null,因此您必须处理它。
回答by siger
Have you tried splitting the string per "\", and then reconstructing a new path by joining every element but the last one?
您是否尝试过按“\”分割字符串,然后通过连接除最后一个元素之外的每个元素来重建新路径?
You would also need to consider the case where the original path is at the root, and when it ends in a backslash or not.
您还需要考虑原始路径位于根目录的情况,以及它何时以反斜杠结尾。
回答by Jason Meckley
This should account for the path being either a file or directory
这应该说明路径是文件还是目录
DirectoryInfo parent = null;
if (File.Exists(path))
{
parent = new FileInfo(path).Directory.Directory
}
if(Directory.Exists(path))
{
parent = new DirectoryInfo(path).Directory;
}
回答by Brandon
System.IO.DirectoryInfois probably the cleanest way to accomplish what you're asking for.
System.IO.DirectoryInfo可能是完成您所要求的最干净的方式。
var path = "\\ServerName\Documents\MasterDocumentFolder\";
string newPath = new DirectoryInfo(path).Parent.CreateSubdirectory("NewDocumentFolder1").FullName;
Console.WriteLine(newPath.FullName);
//> "\ServerName\Documents\NewDocumentFolder1\"
Note that DirectoryInfo does NOT require an existing or accessible directory:
请注意, DirectoryInfo 不需要现有或可访问的目录:
var dir = new DirectoryInfo(@"C:\Asdf\Qwer\Zxcv\Poiu\Lkj\Mn");
Console.WriteLine( dir.Exists );
//> False
But making sure it exists is a snap
但确保它存在是一个瞬间
var dir = new DirectoryInfo(@"C:\Asdf\Qwer\Zxcv\Poiu\Lkj\Mn");
dir.Create();
Console.WriteLine( dir.Exists );
//> True
It will also do nifty things like resolve relative paths:
它还会做一些漂亮的事情,比如解析相对路径:
var dir = new DirectoryInfo(@"C:\Asdf\Qwer\Zxcv\Poiu\Lkj\..\..\..\Mn");
Console.WriteLine( dir.FullName );
//> C:\Asdf\Qwer\Mn
Regarding other answers trimming and appending slashes, note the difference in behavior between Directory.GetParent("...\") and DirectoryInfo("...\").Parent when dealing with trailing \'s - DirectoryInfo is more consistent:
关于修剪和附加斜杠的其他答案,请注意 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
Again, to avoid dealing with trailing slashes, always use Path.Combine() to concatenate paths and file names. It will handle paths correctly whether they contain a trailing \ or not:
同样,为了避免处理尾部斜杠,请始终使用 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
回答by Andrew
With this method you can create dir by dirPath (if dir is not exist) and to create directory from the filePath if needed
使用此方法,您可以通过 dirPath 创建 dir(如果 dir 不存在)并在需要时从 filePath 创建目录
private void CreateDirIfNotExist(string dirPath, bool removeFilename = false)
{
if (removeFilename)
dirPath = Directory.GetParent(dirPath).FullName;
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
}
回答by SteveCinq
In VB:
在VB中:
Dim MyNewPath As String = StrReverse(Strings.Split(StrReverse(MyPath), "\", 2)(1))
This works down to the root, eg C:\MyPathbut fails (without validation) for a bare folder.
这适用于根目录,例如C:\MyPath但对于裸文件夹失败(未经验证)。
Obviously, you need to handle differently if there is a file appended.
显然,如果附加了文件,您需要进行不同的处理。

