0

I want to get the all the files sizes from the directory that I pass to the class and I want them to be sorted by their extension for example:

.exe:  
file1.exe ....... 254KB
file1.exe ....... 544KB
file1.exe ....... 254KB

If their was any other extensions want them to be written like this

Below is the code I wrote so far but I don't know how to sort the data:

public FileTools(string directoryPath,string searchPattern)
{
    DirectoryPath = directoryPath;
    SearchPattern = searchPattern;
    TotallFiles = new List<FileInfo>();
    CalculateFiles();
}
private void CalculateFiles()
{
  foreach (var item in new DirectoryInfo(this.DirectoryPath).GetFiles(SearchPattern,SearchOption.AllDirectories))
     {

     }
 }

I want the FileInfo objects filled in a List and then sort and write them like the example.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
DeadlyDagger
  • 599
  • 4
  • 12
  • 28
  • 1
    And what have you tried so far? The internet is CHOCK FULL of example code demonstrating how to sort collections. – Sam Axe Nov 05 '13 at 10:09
  • Duplicate of [C#.NET :How to Sort a List by a property in the object](http://stackoverflow.com/questions/3309188/c-net-how-to-sort-a-list-t-by-a-property-in-the-object). – CodeCaster Nov 05 '13 at 10:21

3 Answers3

0

Group your files by extension, and order the groups. Then you can have the output by looping on each extension. See this sample:

private void CalculateFiles()
{
    var builder = new StringBuilder();
    var fileGroupByExtension = new DirectoryInfo(this.DirectoryPath)
                                    .GetFiles(SearchPattern,SearchOption.AllDirectories)
                                    .GroupBy(file => file.Extension)
                                    .OrderBy(grp => grp.Key);
    foreach (var grp in fileGroupByExtension)
    {
        var extension = grp.Key;
        builder.Append(extension);
        builder.Append(":");
        builder.AppendLine();
        foreach (var file in grp.OrderBy(file => file.Name))
        {
            builder.Append(file.Name);
            builder.Append(" ....... ");
            builder.Append(file.Length / 1000);
            builder.Append("KB");
            builder.AppendLine();
        }
    }
    Console.Write(builder.ToString());
}
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
0

Try this;

    var sortedList = Directory.EnumerateFiles(
        directoryPath, 
        searchPattern, 
        SearchOption.AllDirectories)
        .OrderBy(item => Path.GetExtension(item));

Remember to include using System.Linq;

Frode
  • 3,325
  • 1
  • 22
  • 32
0

This should work, using LINQ:

var files = new DirectoryInfo(this.DirectoryPath).GetFiles(SearchPattern,SearchOption.AllDirectories);
var ordered_files = from f in files
                    orderby f.Extension
                    select f;
Tobberoth
  • 9,327
  • 2
  • 19
  • 17