如何查询一组文件夹中的总字节数 (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;  
    }  
}
相关推荐
lzb_kkk16 天前
【MFC】编辑框、下拉框、列表控件
c语言·开发语言·c++·mfc·1024程序员节
lzb_kkk17 天前
【MFC】树控件的使用详解
开发语言·c++·windows·mfc·1024程序员节
SizeTheMoment1 个月前
List介绍
1024程序员节
开利网络1 个月前
产业互联网+三融战略:重构企业增长密码
大数据·运维·服务器·人工智能·重构·1024程序员节
wei_shuo2 个月前
从数据中台到数据飞轮:实现数据驱动的升级之路
1024程序员节·数据飞轮
玖剹2 个月前
矩阵区域和 --- 前缀和
数据结构·c++·算法·leetcode·矩阵·动态规划·1024程序员节
jamison_13 个月前
文心一言与 DeepSeek 的竞争分析:技术先发优势为何未能转化为市场主导地位?
人工智能·ai·chatgpt·gpt-3·1024程序员节
NaZiMeKiY3 个月前
HTML5前端第六章节
前端·html·html5·1024程序员节
jamison_13 个月前
颠覆未来:解锁ChatGPT衍生应用的无限可能(具体应用、功能、付费模式与使用情况)
ai·chatgpt·1024程序员节
NaZiMeKiY3 个月前
HTML5前端第七章节
1024程序员节