Jacky
Jacky

Reputation: 114

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

May I know is there any way to get file names from a folder while consuming less memory?

I only knows these two ways, and I can't find an efficient way:

string[] files;

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

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

Upvotes: 0

Views: 162

Answers (1)

Heinzi
Heinzi

Reputation: 172448

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
}

Upvotes: 9

Related Questions