迭代文件夹和子文件夹的最佳方法

发布于 2024-10-19 20:36:48 字数 60 浏览 2 评论 0原文

迭代文件夹和子文件夹以获取从指定位置开始的每个文件夹中的文件大小、文件总数和文件夹总大小的最佳方法是什么?

What's the best way to iterate folders and subfolders to get file size, total number of files, and total size of folder in each folder starting at a specified location?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

暮倦 2024-10-26 20:36:48

如果您使用的是 .NET 4,您可能希望使用 System.IO.DirectoryInfo.EnumerateDirectories 和 System.IO.DirectoryInfo.EnumerateFiles 方法。如果您按照其他帖子的建议使用 Directory.GetFiles 方法,则方法调用将不会返回,直到检索到所有条目。如果您使用递归,这可能需要很长时间。

来自文档

EnumerateFilesGetFiles 方法的区别如下:

  • 当您使用 EnumerateFiles 时,您可以在整个集合被枚举之前开始枚举 FileInfo 对象的集合。
    返回。
  • 使用 GetFiles 时,必须等待返回整个 FileInfo 对象数组,然后才能访问该数组。

因此,当您处理许多文件和目录时,
EnumerateFiles 可以更高效。

If you're using .NET 4, you may wish to use the System.IO.DirectoryInfo.EnumerateDirectories and System.IO.DirectoryInfo.EnumerateFiles methods. If you use the Directory.GetFiles method as other posts have recommended, the method call will not return until it has retrieved ALL the entries. This could take a long time if you are using recursion.

From the documentation:

The EnumerateFilesand GetFiles methods differ as follows:

  • When you use EnumerateFiles, you can start enumerating the collection of FileInfo objects before the whole collection is
    returned.
  • When you use GetFiles, you must wait for the whole array of FileInfo objects to be returned before you can access the array.

Therefore, when you are working with many files and directories,
EnumerateFiles can be more efficient.

ぃ双果 2024-10-26 20:36:48

使用Directory.GetFiles()。该页面的底部包含一个完全递归的示例。

注意:使用 .NET 4 及更高版本时,请使用下面 Chris Dunaway 的答案以获得更现代的方法。

// For Directory.GetFiles and Directory.GetDirectories
// For File.Exists, Directory.Exists
using System;
using System.IO;
using System.Collections;

public class RecursiveFileProcessor 
{
    public static void Main(string[] args) 
    {
        foreach(string path in args) 
        {
            if(File.Exists(path)) 
            {
                // This path is a file
                ProcessFile(path); 
            }               
            else if(Directory.Exists(path)) 
            {
                // This path is a directory
                ProcessDirectory(path);
            }
            else 
            {
                Console.WriteLine("{0} is not a valid file or directory.", path);
            }        
        }        
    }

    // Process all files in the directory passed in, recurse on any directories 
    // that are found, and process the files they contain.
    public static void ProcessDirectory(string targetDirectory) 
    {
        // Process the list of files found in the directory.
        string [] fileEntries = Directory.GetFiles(targetDirectory);
        foreach(string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory.
        string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach(string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }
    
    // Insert logic for processing found files here.
    public static void ProcessFile(string path) 
    {
        Console.WriteLine("Processed file '{0}'.", path);       
    }
}

Use Directory.GetFiles(). The bottom of that page includes an example that's fully recursive.

Note: Use Chris Dunaway's answer below for a more modern approach when using .NET 4 and above.

// For Directory.GetFiles and Directory.GetDirectories
// For File.Exists, Directory.Exists
using System;
using System.IO;
using System.Collections;

public class RecursiveFileProcessor 
{
    public static void Main(string[] args) 
    {
        foreach(string path in args) 
        {
            if(File.Exists(path)) 
            {
                // This path is a file
                ProcessFile(path); 
            }               
            else if(Directory.Exists(path)) 
            {
                // This path is a directory
                ProcessDirectory(path);
            }
            else 
            {
                Console.WriteLine("{0} is not a valid file or directory.", path);
            }        
        }        
    }

    // Process all files in the directory passed in, recurse on any directories 
    // that are found, and process the files they contain.
    public static void ProcessDirectory(string targetDirectory) 
    {
        // Process the list of files found in the directory.
        string [] fileEntries = Directory.GetFiles(targetDirectory);
        foreach(string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory.
        string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach(string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }
    
    // Insert logic for processing found files here.
    public static void ProcessFile(string path) 
    {
        Console.WriteLine("Processed file '{0}'.", path);       
    }
}
菊凝晚露 2024-10-26 20:36:48

迭代所有目录子文件夹和文件,无论子文件夹和文件有多少。

string [] filenames;
 fname = Directory.GetFiles(jak, "*.*", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();

然后从数组中,您可以通过循环或按照您想要的方式获得您想要的内容。

To iterate through all directories sub folders and files, no matter how much sub folder and files are.

string [] filenames;
 fname = Directory.GetFiles(jak, "*.*", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();

then from array you can get what you want via a loop or as you want.

折戟 2024-10-26 20:36:48

这是一个使用 Peter 上面的建议和递归的示例。

using System;
using System.IO;

namespace FileSystemUtils
{
    class Program
    {
        static void Main(string[] args)
        {
            string folderPath = "C:\\docs";

            DirectoryInfo startDir = new DirectoryInfo(folderPath);

            RecurseFileStructure recurseFileStructure = new RecurseFileStructure();
            recurseFileStructure.TraverseDirectory(startDir);
        }

        public class RecurseFileStructure
        {
            public void TraverseDirectory(DirectoryInfo directoryInfo)
            {
                var subdirectories = directoryInfo.EnumerateDirectories();

                foreach (var subdirectory in subdirectories)
                {
                    TraverseDirectory(subdirectory);
                }

                var files = directoryInfo.EnumerateFiles();

                foreach (var file in files)
                {
                    HandleFile(file);
                }
            }

            void HandleFile(FileInfo file)
            {
                Console.WriteLine("{0}", file.Name);
            }
        }
    }
}

Here's an example using Peter's suggestion above and recursion.

using System;
using System.IO;

namespace FileSystemUtils
{
    class Program
    {
        static void Main(string[] args)
        {
            string folderPath = "C:\\docs";

            DirectoryInfo startDir = new DirectoryInfo(folderPath);

            RecurseFileStructure recurseFileStructure = new RecurseFileStructure();
            recurseFileStructure.TraverseDirectory(startDir);
        }

        public class RecurseFileStructure
        {
            public void TraverseDirectory(DirectoryInfo directoryInfo)
            {
                var subdirectories = directoryInfo.EnumerateDirectories();

                foreach (var subdirectory in subdirectories)
                {
                    TraverseDirectory(subdirectory);
                }

                var files = directoryInfo.EnumerateFiles();

                foreach (var file in files)
                {
                    HandleFile(file);
                }
            }

            void HandleFile(FileInfo file)
            {
                Console.WriteLine("{0}", file.Name);
            }
        }
    }
}
瞎闹 2024-10-26 20:36:48

要迭代文件和文件夹,您通常会使用 DirectoryInfoFileInfo 类型。 FileInfo 类型有一个 Length 属性,该属性返回文件大小(以字节为单位)。

我认为您必须编写自己的代码来迭代文件并计算总文件大小,但它应该是一个非常简单的递归函数。

To iterate through files and folders you would normally use the DirectoryInfo and FileInfo types. The FileInfo type has a Length property that returns the file size in bytes.

I think you must write your own code to iterate through the files and calculate the total file size, but it should be a quite simple recursive function.

醉梦枕江山 2024-10-26 20:36:48

请注意,您将需要执行验证检查。

string[] fileNames = Directory.GetFiles("c:\\", "*.*", SearchOption.AllDirectories);
int fileCount = fileNames.Count();
long fileSize = fileNames.Select(file => new FileInfo(file).Length).Sum(); // in bytes

Note that you will need to perform validation checks.

string[] fileNames = Directory.GetFiles("c:\\", "*.*", SearchOption.AllDirectories);
int fileCount = fileNames.Count();
long fileSize = fileNames.Select(file => new FileInfo(file).Length).Sum(); // in bytes
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文