C#实现读取文件夹下全部文件

2025-01-02 03:27:27   小编

C#实现读取文件夹下全部文件

在C#编程中,经常会遇到需要读取文件夹下所有文件的情况,比如批量处理文件、文件内容分析等。本文将介绍如何使用C#实现读取文件夹下全部文件的功能。

我们需要使用System.IO命名空间,它提供了用于文件和目录操作的类和方法。以下是一个简单的示例代码:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string folderPath = @"C:\YourFolderPath";
        ReadFilesInFolder(folderPath);
    }

    static void ReadFilesInFolder(string folderPath)
    {
        try
        {
            string[] files = Directory.GetFiles(folderPath);
            foreach (string file in files)
            {
                Console.WriteLine(file);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("读取文件时出现错误:" + ex.Message);
        }
    }
}

在上述代码中,我们首先定义了一个文件夹路径folderPath,然后调用ReadFilesInFolder方法。在该方法中,使用Directory.GetFiles方法获取文件夹下的所有文件路径,并通过循环遍历输出每个文件的路径。

如果文件夹中还包含子文件夹,并且我们也需要读取子文件夹中的文件,可以使用递归的方式来实现。以下是修改后的代码:

static void ReadFilesInFolderRecursive(string folderPath)
{
    try
    {
        string[] files = Directory.GetFiles(folderPath);
        foreach (string file in files)
        {
            Console.WriteLine(file);
        }

        string[] subfolders = Directory.GetDirectories(folderPath);
        foreach (string subfolder in subfolders)
        {
            ReadFilesInFolderRecursive(subfolder);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("读取文件时出现错误:" + ex.Message);
    }
}

这段代码在获取当前文件夹下的文件后,还会获取子文件夹,并递归调用自身来读取子文件夹中的文件。

通过以上方法,我们可以方便地使用C#读取文件夹下的全部文件,无论是简单的文件列表获取还是复杂的文件处理任务,都可以基于此进行进一步的开发和扩展。

TAGS: 文件处理 文件读取 文件夹操作 C#

欢迎使用万千站长工具!

Welcome to www.zzTool.com