如何按大小对从 GetFiles/GetDirectories 检索到的两个 files/folders 进行排序

How do I sort both files/folders retrieved from GetFiles/ GetDirectories by size

我正在使用 GetFiles 和 GetDirectories 从文件夹浏览器对话框中检索文件。现在我在按大小对文件/目录进行排序时遇到问题。 我尝试了以下方法,但不确定根据它们的大小循环 files/folders 的下一步是什么。

private void Button1_Click(object sender, EventArgs e)
        {
            //open folder dialog
            FolderBrowserDialog FBD = new FolderBrowserDialog();

            if (FBD.ShowDialog() == DialogResult.OK)
            {
                listBox1.Items.Clear();
                //get file name and file info 
                FileInfo[] files = new DirectoryInfo(FBD.SelectedPath).GetFiles();
                //get directory 
                DirectoryInfo[] dirs = new DirectoryInfo(FBD.SelectedPath).GetDirectories();

                //Order by size.
                var sort = from fileName in files
                            orderby new FileInfo(fileName).Length ascending
                            select fileName; 
                //now I have no idea how to apply this sort to the loop below

                foreach (FileInfo file in files)
                {
                    //print single file output eg. filename (300000 bytes)
                    listBox1.Items.Add(file.Name + "(" + file.Length + " bytes)");
                }

                foreach (DirectoryInfo dir in dirs)
                {
                    //print sub folder output eg. foldername (sum of all childfiles sizes) -> (600000 bytes)
                    listBox1.Items.Add(dir.Name + "(" + dir.GetFiles().Sum(f => f.Length) + " bytes)");
                }
            }
        }

该按钮将打开文件夹对话框和显示结果的列表框。

对于文件,您可以执行以下任一操作:

foreach (FileInfo file in sort)

(因为您已经提前创建了 OrderedEnumerable)

foreach (FileInfo file in files.OrderBy(file => file.Length))

按大小对目录进行排序会更加复杂,因为 DirectoryInfo 没有长度 属性。

Kev's answer here 的基础上,您可以尝试:

foreach (DirectoryInfo dir in dirs.OrderBy(dir => dir.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length))