如何从文件路径中获取目录(不包括根目录和文件名) [英] How to get the Directories from the filepath excluding the root and filename

查看:149
本文介绍了如何从文件路径中获取目录(不包括根目录和文件名)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我的文件路径说"C:\ hello \ hi \ dotnet \ abc.txt".我只想要路径中的目录.

预期输出:
你好

dotnet

我使用过Path.DirectorySeparatorChar,但是它不起作用.请帮我解决这个问题.

谢谢
Stone Cold

Hello,

I have a filepath say "C:\hello\hi\dotnet\abc.txt". I just want the directories from the path.

Expected Output :
hello
hi
dotnet

I have used Path.DirectorySeparatorChar but it doesn''t work.So help me out to solve this problem.

Thanks
Stone Cold

推荐答案

您也可以使用 FileInfo.DirectoryName 访问路径的目录部分[^ ] .

您可以访问 FileInfo.Directory [ DirectoryInfo.Name [ DirectoryInfo.Parent [
You may also use the System.IO.FileInfo[^] class. You can then access the directory part of the path using FileInfo.DirectoryName [^].

You can access the FileInfo.Directory[^] which returns a DriveInfo object - use the DirectoryInfo.Name[^] to get the name of the directory, then use DirectoryInfo.Parent[^] to access the parent directory. Repeat until you you have reached the root directory of the drive - i.e. Parent returns null.

Best regards
Espen Harlinn


使用Split并排除0和最后一个条目
Use Split and exclude the 0 and the last entry
string[] dirs = pathname.Split('\\');
//dirs[1] will contain hello etc 


这篇关于如何从文件路径中获取目录(不包括根目录和文件名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆