Skip to main content
 首页 » 编程设计

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

2024年02月23日14mfryf

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

我正在使用 .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.