如何查询一组文件夹中的总字节数 (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;  
    }  
}
相关推荐
freellf8 天前
数据结构及基本算法
1024程序员节
BruceGerGer25 天前
flutter开发实战-flutter web加载html及HtmlElementView的使用
flutter·1024程序员节
网络冒险家2 个月前
【软考】系统集成项目管理工程师【第二版】
职场和发展·软考·集成学习·1024程序员节·系统集成项目工程师
BruceGerGer2 个月前
flutter开发实战-AssetBundle读取指定packagename的文件
flutter·1024程序员节
sheng12345678rui2 个月前
最新缺失msvcp140.dll的多种解决方法,有效解决电脑dll问题
windows·microsoft·电脑·dll文件·1024程序员节
a5553338203 个月前
电脑显示mfc140u.dll丢失的修复方法,总结7种有效的方法
java·经验分享·dll·dll文件丢失·1024程序员节
行十万里人生3 个月前
C++ 智能指针
linux·c++·git·阿里云·容器·蓝桥杯·1024程序员节
a5553338203 个月前
启动鸣潮提示错误代码126:加载d3dcompiler_43.dll错误或缺失的7个解决方法
前端·经验分享·dll·dll文件丢失·1024程序员节
BruceGerGer3 个月前
flutter开发实战-Webview及dispose关闭背景音
flutter·1024程序员节
BruceGerGer3 个月前
flutter开发实战-ListWheelScrollView与自定义TimePicker时间选择器
flutter·1024程序员节