从完整的文件名路径中获取文件夹名称 [英] Getting the folder name from a full filename path

查看:28
本文介绍了从完整的文件名路径中获取文件夹名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string path = "C:folder1folder2file.txt";

我可以使用哪些对象或方法来给我 folder2 的结果?

What objects or methods could I use that would give me a result of folder2?

推荐答案

我可能会使用类似的东西:

I would probably use something like:

string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );

GetDirectoryName 的内部调用将返回完整路径,而对 GetFileName() 的外部调用将返回最后一个路径组件 - 这将是文件夹名称.

The inner call to GetDirectoryName will return the full path, while the outer call to GetFileName() will return the last path component - which will be the folder name.

无论路径是否实际存在,此方法都有效.但是,这种方法确实依赖于最初以文件名结尾的路径.如果不知道路径是以文件名还是文件夹名结尾 - 那么它需要您首先检查实际路径以查看该位置是否存在文件/文件夹.在这种情况下,Dan Dimitru 的回答可能更合适.

This approach works whether or not the path actually exists. This approach, does however, rely on the path initially ending in a filename. If it's unknown whether the path ends in a filename or folder name - then it requires that you check the actual path to see if a file/folder exists at the location first. In that case, Dan Dimitru's answer may be more appropriate.

这篇关于从完整的文件名路径中获取文件夹名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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