How do I retrieve all filenames in a directory?

*爱你&永不变心* 提交于 2019-12-03 15:57:31

问题


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 :)


回答1:


foreach (string s in Directory.GetFiles(path, "*.txt").Select(Path.GetFileName))
       Console.WriteLine(s);



回答2:


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:


Do you want to recurse through subdirectories? Use Directory.EnumerateFiles:

var fileNames = Directory.EnumerateFiles(@"\", "*.*", SearchOption.AllDirectories);



回答4:


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);
}



回答5:


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;
    }



回答6:


var filenames = Directory.GetFiles(@"C:\\Images", "*.jpg").
                Select(filename => Path.GetFileNameWithoutExtension(filename)).
                ToArray();

Try this if it is what you want




回答7:


Try this

IEnumerable<string> fileNames =
                Directory.GetFiles(@"\\srvktfs1\Metin Atalay\", "*.dll")
                    .Select(Path.GetFileNameWithoutExtension);


来源:https://stackoverflow.com/questions/3694676/how-do-i-retrieve-all-filenames-in-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!