如何在C#中的目录中获取文件名 [英] How to get the name of File in a directory in C#

查看:74
本文介绍了如何在C#中的目录中获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Directory.GetFiles(targetDirectory);

使用上面的代码,我们获得目录中所有文件的名称(即完整路径).但我只需要获取文件名而不是路径.那么,如何单独获取文件名(不包括路径)呢?还是在删除不需要的部分时需要执行字符串操作?

Using the above code we get the names(i.e full path) of all the files in the directory. but i need to get only the name of the file and not the path. So how can I get the name of the files alone excluding the path? Or do I need to do the string operations in removing the unwanted part?

TreeNode mNode = new TreeNode(ofd.FileName, 2, 2);

这里 ofd 是一个 OpenFileDialog ,而 ofd.FileName 给出了文件名及其路径,但我只需要文件名.

Here ofd is a OpenFileDialog and ofd.FileName is giving the the filename along with it's Path but I need the file name alone.

推荐答案

您可以使用:

Path.GetFileName(fullPath);

或在您的示例中:

TreeNode mNode = new TreeNode(Path.GetFileName(ofd.FileName), 2, 2);

这篇关于如何在C#中的目录中获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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