gpt4 book ai didi

C# - 如何快速、优化地列出子目录中的文件

转载 作者:太空宇宙 更新时间:2023-11-03 22:08:20 24 4
gpt4 key购买 nike

我正在尝试使用以下方法列出根目录的所有子目录中的文件。但是当文件数量以百万计时,它会花费很多时间。有没有更好的方法来做到这一点。

我正在使用 .NET 3.5,所以不能使用枚举器:-(

        ******************* Main *************
DirectoryInfo dir = new DirectoryInfo(path);
DirectoryInfo[] subDir = dir.GetDirectories();
foreach (DirectoryInfo di in subDir) //call for each sub directory
{
PopulateList(di.FullName, false);
}

*******************************************
static void PopulateList(string directory, bool IsRoot)
{

System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "dir /s/b \"" + directory + "\"");
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();

string fileName = directory.Substring(directory.LastIndexOf('\\') + 1);
StreamWriter writer = new StreamWriter(fileName + ".lst");

while (proc.StandardOutput.EndOfStream != true)
{
writer.WriteLine(proc.StandardOutput.ReadLine());
writer.Flush();
}
writer.Close();
}

最佳答案

删除所有与流程相关的内容并尝试 Directory.GetDirectories ()Directory.GetFiles()方法:

public IEnumerable<string> GetAllFiles(string rootDirectory)
{
foreach(var directory in Directory.GetDirectories(
rootDirectory,
"*",
SearchOption.AllDirectories))
{
foreach(var file in Directory.GetFiles(directory))
{
yield return file;
}
}
}

来自 MSDN,SearchOption.AllDirectories:

Includes the current directory and all the subdirectories in a search operation. This option includes reparse points like mounted drives and symbolic links in the search.

关于C# - 如何快速、优化地列出子目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7596747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com