如何查询一组文件夹中的总字节数 (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;  
    }  
}
相关推荐
金融小师妹1 小时前
基于LSTM-GARCH混合模型:降息预期驱动金价攀升,白银刷新历史峰值的蒙特卡洛模拟验证
大数据·人工智能·深度学习·1024程序员节
普通网友2 小时前
‌Flutter vs Kotlin:移动开发的未来趋势与选择
1024程序员节
我来整一篇6 小时前
[油猴脚本] 微软必应奖励每日任务脚本
1024程序员节
金融小师妹6 小时前
AI视角下黄金避风港属性的量化验证:基于2000-2025年历史数据的时序分析
大数据·人工智能·深度学习·1024程序员节
君以思为故7 小时前
认识linux -- 进程控制
linux·运维·1024程序员节
CoderYanger10 小时前
递归、搜索与回溯-记忆化搜索:40.矩阵中的最长递增路径
java·线性代数·算法·leetcode·矩阵·1024程序员节
xcLeigh12 小时前
KingbaseES数据库:首个多院区异构多活容灾架构,浙人医创新开新篇
国产数据库·1024程序员节·kingbasees·金仓数据库
熊文豪12 小时前
首个多院区异构多活容灾架构,浙人医创新开新篇
1024程序员节·kingbase·电科金仓
tg-zm88999620 小时前
2025返利商城源码/挂机自动收益可二开多语言/自定义返利比例/三级分销理财商城
java·mysql·php·laravel·1024程序员节
CoderYanger1 天前
递归、搜索与回溯-综合练习:19.目标和
java·算法·leetcode·1024程序员节