如何查询一组文件夹中的总字节数 (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;  
    }  
}
相关推荐
学传打活3 天前
【边打字.边学昆仑正义文化】_19_星际生命的生存状况(1)
微信公众平台·1024程序员节·汉字·昆仑正义文化
unable code10 天前
[HNCTF 2022 WEEK2]ez_ssrf
网络安全·web·ctf·1024程序员节
unable code11 天前
[NISACTF 2022]easyssrf
网络安全·web·ctf·1024程序员节
unable code12 天前
BUUCTF-[第二章 web进阶]SSRF Training
网络安全·web·ctf·1024程序员节
开开心心就好13 天前
进程启动瞬间暂停工具,适合调试多开
linux·运维·安全·pdf·智能音箱·智能手表·1024程序员节
仰泳之鹅14 天前
【51单片机】第一课:单片机简介与软件安装
单片机·嵌入式硬件·51单片机·1024程序员节
海海不瞌睡(捏捏王子)14 天前
C#知识点概要
java·开发语言·1024程序员节
小浣熊熊熊熊熊熊熊丶15 天前
飞牛NAS 安装 Teslamate 教程(docker版)
1024程序员节
程高兴15 天前
模糊PID控制的永磁同步电机矢量控制系统-SIMULINK
matlab·1024程序员节
海海不瞌睡(捏捏王子)16 天前
Unity知识点概要
unity·1024程序员节