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

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

本文介绍了迭代文件夹和子文件夹的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

// 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);
    }
}

这篇关于迭代文件夹和子文件夹的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!