0

我想从传递给类的目录中获取所有文件大小,并且希望它们按扩展名排序,例如:

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

如果他们有任何其他扩展希望他们这样写

以下是我到目前为止编写的代码,但我不知道如何对数据进行排序:

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))
     {

     }
 }

我希望将FileInfo对象填写在 a 中List,然后像示例一样对它们进行排序和编写。

4

3 回答 3

0

按扩展名对文件进行分组,并对组进行排序。然后,您可以通过在每个扩展上循环来获得输出。请参阅此示例:

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());
}
于 2013-11-05T10:14:20.387 回答
0

尝试这个;

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

记得包括using System.Linq;

于 2013-11-05T10:14:59.900 回答
0

这应该工作,使用 LINQ:

var files = new DirectoryInfo(this.DirectoryPath).GetFiles(SearchPattern,SearchOption.AllDirectories);
var ordered_files = from f in files
                    orderby f.Extension
                    select f;
于 2013-11-05T10:15:04.317 回答