如何查询一组文件夹中的总字节数 (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;  
    }  
}
相关推荐
学传打活8 小时前
【边打字.边学昆仑正义文化】_5_宇宙物种创造简史(1)
微信公众平台·1024程序员节·汉字·昆伦正义文化
xcLeigh1 天前
打破机房围墙:VMware+cpolar构建跨网络虚拟实验室
vmware·内网穿透·cpolar·实验室·远程访问·1024程序员节
开开心心就好3 天前
免费轻量电子书阅读器,多系统记笔记听书
linux·运维·服务器·安全·ddos·可信计算技术·1024程序员节
unable code4 天前
流量包取证-大流量分析
网络安全·ctf·misc·1024程序员节·流量包取证
开开心心就好4 天前
实用PDF擦除隐藏信息工具,空白处理需留意
运维·服务器·windows·pdf·迭代器模式·桥接模式·1024程序员节
unable code5 天前
浏览器取证-[GKCTF 2021]FireFox Forensics
网络安全·ctf·misc·1024程序员节·浏览器取证
unable code5 天前
内存取证-[安洵杯 2019]Attack
网络安全·ctf·misc·1024程序员节·内存取证
unable code5 天前
CTF-SPCS-Forensics
网络安全·ctf·misc·1024程序员节·取证
unable code6 天前
内存取证-卡比卡比卡比
网络安全·ctf·misc·1024程序员节·内存取证