sort files by size error in c#

故事扮演 提交于 2021-02-05 12:28:33

问题


I have a little problem sorting files.

My program should allow me to sort the files of a directory by size and by date. The date works fine but when I try to sort by size, it returns an error.

This is my relevant code:

if (orden.Equals("tam"))
{
    ficheroo = dirInfoo.GetFiles(filtro, SearchOption.AllDirectories).OrderBy(f => new FileInfo(f).Length).ToList();
}

the error is in the use of new FileInfo(f).Length and the error is:

La mejor coincidencia de método sobrecargado para 'System.IO.FileInfo.FileInfo(string)' tiene algunos argumentos no válidos

This translates to:

The best overloaded method match for 'System.IO.FileInfo.FileInfo (string)' has some invalid arguments


回答1:


DirectoryInfo.GetFiles already returns a FileInfo[] - so you don't need to convert each entry into a FileInfo using the constructor, as you're trying to do now. You can just use:

ficheroo = dirInfoo.GetFiles(filtro, SearchOption.AllDirectories)
                   .OrderBy(f => f.Length)
                   .ToList();

(As a side note, it's worth seeing how using vertical space makes your code easier to read than having everything on one enormous line.)




回答2:


GetFiles already returns FileInfo, I suspect you want

 dirInfoo.GetFiles(filtro, SearchOption.AllDirectories)
                     .OrderBy(f => f.Length).ToList();



回答3:


You are getting a compilation error because GetFiles already returns a FileInfo array. So you don't need to create new FileInfos in the OrderBy clause.

ficheroo = dirInfoo.GetFiles(filtro, SearchOption.AllDirectories).OrderBy(f => f.Length).ToList();


来源:https://stackoverflow.com/questions/24258853/sort-files-by-size-error-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!