我想从我传递给类的目录中获取所有文件大小,并且我希望它们按其扩展名进行排序,例如:
.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
中填充List
个对象,然后按照示例对它们进行排序和编写。
答案 0 :(得分: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());
}
答案 1 :(得分:0)
试试这个;
var sortedList = Directory.EnumerateFiles(
directoryPath,
searchPattern,
SearchOption.AllDirectories)
.OrderBy(item => Path.GetExtension(item));
请记住加入using System.Linq;
答案 2 :(得分:0)
这应该可以使用LINQ:
var files = new DirectoryInfo(this.DirectoryPath).GetFiles(SearchPattern,SearchOption.AllDirectories);
var ordered_files = from f in files
orderby f.Extension
select f;