如何查询一组文件夹中的总字节数 (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;  
    }  
}
相关推荐
fruge34 分钟前
Less:让CSS开发更简单的预处理器
1024程序员节
月临水1 小时前
Git 学习笔记
笔记·git·学习·1024程序员节
MeowKnight9581 小时前
【C】占位符知识点总结
1024程序员节
春日见1 小时前
“package.xml”和“CMakeLists.txt”配置
1024程序员节
Felven2 小时前
统信系统下设置RTC时间
linux·rtc·1024程序员节
程序猿阿伟2 小时前
《3D端游开放世界动态天气系统与场景交互优化实践日志》
3d·1024程序员节
#麻辣小龙虾#2 小时前
基于transform的scale属性,实现数据可视化大屏自适应缩放适配不同分辨率
1024程序员节
2301_772093562 小时前
KVSTORE_Pain point_tuchuang_ROS2
java·开发语言·1024程序员节
cyyt2 小时前
深度学习周报(10.20~10.26)
1024程序员节