Fastest way to count folder files in .NET 4.0

自古美人都是妖i 提交于 2019-12-13 03:05:10

问题


I need to count the number of files in a folder in .NET 4: The count will return number of all files except the .db file in the folder.

Option 1:

 IEnumerable<string> enumerables = Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
 int iNumFiles = 0; 
 foreach (string f in enumerables)
 {
    if (!f.EndsWith(".db"))
       iNumFiles++;
 }

 //iNumFiles is the count

Option 2:

int iNumFiles = 0; 
IEnumerable<string> enumerables1 = Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
IEnumerable<string> enumerables2 = Directory.EnumerateFiles(strPath, "*.db", SearchOption.TopDirectoryOnly);

iNumFiles = enumerables1.Count() - enumerables2.Count();

//iNumFiles is the count

Is there any other simpler but better methods (using RegEx or something else) that I should use?

EDIT: Should I keep the .db file or how useful it is? All I know it is the database (cache) of folder contents.

This is messing up my file count.

Thanks for reading.


回答1:


Turn the . results into a queryable object. then query out the *.db items.

var queryObject = My.Computer.FileSystem.getFiles(foldername, FileIO.SearchOption.SearchTopLevelOnly, "*.*").AsQueryable();

var filesIcareAbout = queryObject.where(f => right(f,3) != ".db");

I took some syntax shorcuts. This may not be exactly right syntactically.




回答2:


new DirectoryInfo(strPath).EnumerateFiles("*.db").Count();


来源:https://stackoverflow.com/questions/4764033/fastest-way-to-count-folder-files-in-net-4-0

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