如何查询一组文件夹中的总字节数 (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;  
    }  
}
相关推荐
earthzhang20212 天前
《深入浅出HTTPS》读书笔记(31):HTTPS和TLS/SSL
开发语言·网络·python·https·1024程序员节
不讲废话的小白4 天前
怎么样把pdf转成图片模式(不能复制文字)
pdf·1024程序员节
明明真系叻5 天前
2025.1.26机器学习笔记:C-RNN-GAN文献阅读
人工智能·笔记·深度学习·机器学习·生成对抗网络·1024程序员节
Joeysoda9 天前
Java数据结构 (从0构建链表(LinkedList))
java·linux·开发语言·数据结构·windows·链表·1024程序员节
清风-云烟11 天前
使用redis-cli命令实现redis crud操作
java·linux·数据库·redis·spring·缓存·1024程序员节
Joeysoda11 天前
Java数据结构 (链表反转(LinkedList----Leetcode206))
java·linux·开发语言·数据结构·链表·1024程序员节
比特在路上12 天前
StackOrQueueOJ3:用栈实现队列
c语言·开发语言·数据结构·1024程序员节
0xCC说逆向13 天前
Windows图形界面(GUI)-QT-C/C++ - Qt键盘与鼠标事件处理详解
c语言·开发语言·c++·windows·qt·win32·1024程序员节
明明真系叻14 天前
2025.1.18机器学习笔记:PINN文献精读
人工智能·笔记·深度学习·机器学习·1024程序员节
0xCC说逆向15 天前
Windows图形界面(GUI)-QT-C/C++ - Qt List Widget详解与应用
c语言·开发语言·c++·windows·qt·win32·1024程序员节