How do I retrieve all filenames in a directory?

2020-06-08 13:14发布

How do I retrieve all filenames matching a pattern in a directory? I tried this but it returns the full path instead of the filename.

Directory.GetFiles (path, "*.txt")

Do I have to manually crop the directory path off of the result? It's easy but maybe there is an even simpler solution :)

7条回答
别忘想泡老子
2楼-- · 2020-06-08 13:46

Assuming you're using C#, the DirectoryInfo class will be of more use to you:

DirectoryInfo directory = new DirectoryInfo(path);
FileInfo[] files = directory.GetFiles("*.txt");

The FileInfo class contains a property Name which returns the name without the path.

See the DirectoryInfo documentation and the FileInfo documentation for more information.

查看更多
祖国的老花朵
3楼-- · 2020-06-08 13:46

You can use the following code to obtain the filenames:

    DirectoryInfo info  = new DirectoryInfo("C:\Test");
    FileInfo[] files = info.GetFiles("*.txt");

    foreach(FileInfo file in files)
    {
        string fileName = file.Name;
    }
查看更多
霸刀☆藐视天下
4楼-- · 2020-06-08 13:47
var filenames = Directory.GetFiles(@"C:\\Images", "*.jpg").
                Select(filename => Path.GetFileNameWithoutExtension(filename)).
                ToArray();

Try this if it is what you want

查看更多
疯言疯语
5楼-- · 2020-06-08 13:58

Try this

IEnumerable<string> fileNames =
                Directory.GetFiles(@"\\srvktfs1\Metin Atalay\", "*.dll")
                    .Select(Path.GetFileNameWithoutExtension);
查看更多
Evening l夕情丶
6楼-- · 2020-06-08 14:10
foreach (string s in Directory.GetFiles(path, "*.txt").Select(Path.GetFileName))
       Console.WriteLine(s);
查看更多
戒情不戒烟
7楼-- · 2020-06-08 14:11

Use Path.GetFileName with your code:

foreach(var file in Directory.GetFiles(path, "*.txt"))
{
   Console.WriteLine(Path.GetFileName(file));
}

Another solution:

DirectoryInfo dir = new DirectoryInfo(path);
var files = dir.GetFiles("*.txt");
foreach(var file in files)
{
   Console.WriteLine(file.Name);
}
查看更多
登录 后发表回答