1

I am using GetFiles and GetDirectories to retrieve files from a folder browser dialog. Now I have a problem with sorting the files/ directories by the size. I tried the following method but doesn't sure what is the next step to loop both files/folders based on their size.

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)");
                }
            }
        }

The button will open a folder dialog, and a listbox to display the result.

Alois
  • 130
  • 1
  • 2
  • 14
  • Im not sure i get what u mean, u already sorted by size in `sort` variable, why u want to do it again on loop, and please note that u are using the old `files` in foreach rather than `sort` which is sort result. – hessam hedieh Sep 12 '19 at 07:22

1 Answers1

3

For the files, you can do either of the following:

foreach (FileInfo file in sort)

(since you already created the OrderedEnumerable ahead of time)

or

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

Sorting the directories by size would be more involved, as DirectoryInfo does not have a Length property.

Building on Kev's answer here, you could try:

foreach (DirectoryInfo dir in dirs.OrderBy(dir => dir.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length))
Kei
  • 1,026
  • 8
  • 15