What is the cheaper way to get file names in a folder in C#?

133 Views Asked by At

I'm trying to find a way which consume less memory to get file names from a folder.

I tried these two methods (both works), but I don't know which is cheaper:

        string[] files;

        //method 1
        files = new DirectoryInfo(root)
            .GetFiles()
            .Select(f => f.Name).ToArray();

        //method 2
        files = Directory.GetFiles(root);
        for (int i = 0; i < files.Length; i++)
            files[i] = Path.GetFileName(files[i]);
1

There are 1 best solutions below

1
On BEST ANSWER

None of those two. Both create an in-memory array containing all file names.

If memory is really that scarce (hint: it usually isn't), you can use Directory.EnumerateFiles to iterate through all the file names without keeping the whole list in memory:

foreach(var path in Directory.EnumerateFiles(root))
{
    var fileName = Path.GetFileName(path);

    // do whatever needs to be done with that file name
}