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