简体   繁体   中英

How do I retrieve all filenames in a directory?

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

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

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.

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

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

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);
}
var filenames = Directory.GetFiles(@"C:\\Images", "*.jpg").
                Select(filename => Path.GetFileNameWithoutExtension(filename)).
                ToArray();

Try this if it is what you want

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

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM