如何在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);