如何开始使用C#中的目录中唯一的文件名? [英] How to get only filenames within a directory using c#?

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

问题描述

当我用code线如下,我得到一个字符串数组,包含各个文件的完整路径。

When I use the line of code as below , I get an string array containing the entire path of the individual files .

private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf");

我想知道是否有一种方法可以只在检索字符串而不是整个路径的文件名。

I would like to know if there is a way to only retrieve the file names in the strings rather than the entire paths.

推荐答案

您可以使用<一个href="http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx"><$c$c>Path.GetFileName从完整的路径得到的文件名

You can use Path.GetFileName to get the filename from the full path

private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf")
                                     .Select(path => Path.GetFileName(path))
                                     .ToArray();


编辑:上述解决方案使用 LINQ ,所以它需要.NET 3.5最少。这里有一个解决方案,在早期版本的作品:


the solution above uses LINQ, so it requires .NET 3.5 at least. Here's a solution that works on earlier versions:

private string[] pdfFiles = GetFileNames("C:\\Documents", *.pdf");

private static string[] GetFileNames(string path, string filter)
{
    string[] files = Directory.GetFiles(path, filter);
    for(int i = 0; i < files.Length; i++)
        files[i] = Path.GetFileName(files[i]);
    return files;
}

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

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