如何从路径字符串获取最后一个文件夹? [英] How can I get the last folder from a path string?

查看:304
本文介绍了如何从路径字符串获取最后一个文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的目录:

I have a directory that looks something like this:

C:\Users\me\Projects\

在我的应用程序中,我将给定的项目名称附加到该路径:

In my application, I append to that path a given project name:

C:\Users\me\Projects\myProject

之后,我希望能够将其传递给方法.在此方法中,我还要使用项目名称.解析路径字符串以获得上一个文件夹名称的最佳方法是什么?

After, I want to be able to pass that into a method. Inside this method I would also like to use the project name. What is the best way to parse the path string to get the last folder name?

我知道一种解决方法是将路径和项目名称传递给函数,但是我希望可以将其限制为一个参数.

I know a work-around would be to pass the path and the project name into the function, but I was hoping I could limit it to one parameter.

推荐答案

您可以这样做:

string dirName = new DirectoryInfo(@"C:\Users\me\Projects\myProject\").Name;

或使用Path.GetFileName之类的(有点hack):

string dirName2 = Path.GetFileName(
              @"C:\Users\me\Projects\myProject".TrimEnd(Path.DirectorySeparatorChar));

Path.GetFileName 返回路径中的文件名,如果路径以\结尾,则它将返回一个空字符串,这就是为什么我使用TrimEnd(Path.DirectorySeparatorChar)

Path.GetFileName returns the file name from the path, if the path is terminating with \ then it would return an empty string, that is why I have used TrimEnd(Path.DirectorySeparatorChar)

这篇关于如何从路径字符串获取最后一个文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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