繁体   English   中英

从文件夹路径获取最后 2 个文件夹名称

[英]Getting last 2 folder names from folder path

如何从 C# 的文件夹路径中获取最后 2 个文件夹的名称?

文件夹路径例如: C:\test\documents\pdf\example.pdf

我想要documents\pdf 我需要使用什么 object 或方法?

编辑:到目前为止,我已经尝试过string currentDirectory = System.IO.Path.GetDirectoryName(path);

但是当我只想要最后 2 个目录时,它会返回整个路径。 添加string Folder = Directory.GetParent(currentDirectory).Name;

返回父文件夹documents ,但不返回documents/pdf

有很多方法可以做到这一点。

一个例子:

var yourDir = "C:\\test\\documents\\pdf\\";

// Get a DirectoryInfo object representing C:\\test\\documents\\pdf:
var yourDirInfo = new DirectoryInfo(yourDir); 

// Get "documents\\pdf":
var combined = yourDirInfo.Parent.Name + Path.DirectorySeparatorChar + yourDirInfo.Name

您可以使用 GetDirectoryName ,它将返回不带文件名的完整路径

string path = "C:/test/documents/pdf/example.pdf";    
string dir = Path.GetDirectoryName(path);

然后用'/'分割路径并取数组的最后两个元素

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM