[英]What is the cheaper way to get file names in a folder in C#?
I'm trying to find a way which consume less memory to get file names from a folder.我正在尝试找到一种消耗更少 memory 的方法来从文件夹中获取文件名。
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:如果 memory真的那么稀缺(提示:通常不是),您可以使用
Directory.EnumerateFiles
遍历所有文件名,而不用将整个列表保留在 memory 中:
foreach(var path in Directory.EnumerateFiles(root))
{
var fileName = Path.GetFileName(path);
// do whatever needs to be done with that file name
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.