如何查询一组文件夹中的总字节数 (LINQ) (C#)

cs 复制代码
class QuerySize  
{  
    public static void Main()  
    {  
        string startFolder = @"c:\program files\Microsoft Visual Studio 9.0\VC#";  
  
        // Take a snapshot of the file system.  
        // This method assumes that the application has discovery permissions  
        // for all folders under the specified path.  
        IEnumerable<string> fileList = System.IO.Directory.GetFiles(startFolder, "*.*", System.IO.SearchOption.AllDirectories);  
  
        var fileQuery = from file in fileList  
                        select GetFileLength(file);  
  
        // Cache the results to avoid multiple trips to the file system.  
        long[] fileLengths = fileQuery.ToArray();  
  
        // Return the size of the largest file  
        long largestFile = fileLengths.Max();  
  
        // Return the total number of bytes in all the files under the specified folder.  
        long totalBytes = fileLengths.Sum();  
  
        Console.WriteLine("There are {0} bytes in {1} files under {2}",  
            totalBytes, fileList.Count(), startFolder);  
        Console.WriteLine("The largest files is {0} bytes.", largestFile);  
  
        // Keep the console window open in debug mode.  
        Console.WriteLine("Press any key to exit.");  
        Console.ReadKey();  
    }  
  
    // This method is used to swallow the possible exception  
    // that can be raised when accessing the System.IO.FileInfo.Length property.  
    static long GetFileLength(string filename)  
    {  
        long retval;  
        try  
        {  
            System.IO.FileInfo fi = new System.IO.FileInfo(filename);  
            retval = fi.Length;  
        }  
        catch (System.IO.FileNotFoundException)  
        {  
            // If a file is no longer present,  
            // just add zero bytes to the total.  
            retval = 0;  
        }  
        return retval;  
    }  
}
相关推荐
yBmZlQzJ1 天前
财运到内网穿透域名解析技术机制与中立评估
运维·经验分享·docker·容器·1024程序员节
yBmZlQzJ1 天前
内网穿透工具通过端口转发实现内外网通信
运维·经验分享·docker·容器·1024程序员节
数据皮皮侠AI2 天前
数字经济政策工具变量数据(2008-2023)
大数据·数据库·人工智能·笔记·1024程序员节
网安_秋刀鱼2 天前
【java安全】shiro反序列化1(shiro550)
java·开发语言·安全·web安全·网络安全·1024程序员节
unable code4 天前
攻防世界-Misc-Wire1
网络安全·ctf·misc·1024程序员节
开开心心就好5 天前
版本转换工具,支持Win双系统零售批量版
linux·运维·服务器·pdf·散列表·零售·1024程序员节
开开心心就好5 天前
免费卸载工具,可清理残留批量管理启动项
linux·运维·服务器·windows·随机森林·pdf·1024程序员节
unable code5 天前
攻防世界-Misc-4-1
网络安全·ctf·misc·1024程序员节
yBmZlQzJ7 天前
免费内网穿透-端口转发配置介绍
运维·经验分享·docker·容器·1024程序员节
金融小师妹8 天前
AI算法视角下非农夜冲击波来袭,黄金高位区间震荡态势的深度神经网络解析
大数据·深度学习·1024程序员节