如何查询一组文件夹中的总字节数 (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;  
    }  
}
相关推荐
开开心心就好16 小时前
轻松加密文件生成exe,无需原程序解密
linux·运维·服务器·windows·pdf·harmonyos·1024程序员节
unable code16 小时前
内存取证-easy_mem_3
网络安全·ctf·misc·1024程序员节·内存取证
开开心心就好17 小时前
高效U盘容量检测工具,一键辨真假,防假货
linux·运维·服务器·线性代数·安全·抽象代数·1024程序员节
unable code18 小时前
内存取证-easy_mem_2
网络安全·ctf·misc·1024程序员节·内存取证
unable code1 天前
内存取证-easy_mem_1
网络安全·ctf·misc·1024程序员节·内存取证
开开心心就好8 天前
发票合并打印工具,多页布局设置实时预览
linux·运维·服务器·windows·pdf·harmonyos·1024程序员节
开开心心就好13 天前
开源免费高速看图工具,支持漫画大图秒开
linux·运维·服务器·安全·ruby·symfony·1024程序员节
unable code16 天前
磁盘取证-Flying_High
网络安全·ctf·misc·1024程序员节·磁盘取证
unable code16 天前
磁盘取证-ColorfulDisk
网络安全·ctf·misc·1024程序员节·内存取证
unable code17 天前
磁盘取证-[第十章][10.1.2 磁盘取证方法]磁盘取证1
网络安全·ctf·misc·1024程序员节·内存取证