C# 遍历读取某个目录文件夹下的不同类型子文件和其子文件夹(里面可能又有许多文件)

本文介绍了一种通过指定目录来遍历其中的所有文件及子文件夹的方法,并针对特定类型如.mdb和.gdb文件进行了处理。对于文件,可以通过扩展进行筛选;对于文件夹,则进一步递归处理。

首先获取到文件目录,这里是参数targetDirectory传递进来:

//对该路径下的文件进行遍历,获取文件名 

string[] fileEntries = Directory.GetFiles(targetDirectory);

                foreach (string fileName in fileEntries)
                    if (fileName.EndsWith(".mdb"))  // 比较不同点: mdb是一种文件,而gdb是文件夹,里面包含多个文件

                        messagebox.Show(fileName); //这里仅仅是弹框显示文件名,可以换成别的复杂功能。

                        if (fileName.EndsWith(".txt"))  // 比较不同点: mdb是一种文件,而gdb是文件夹,里面包含多个文件

                        messagebox.Show(fileName); 


                    //此处可以写代码:添加if判断,显示txt等其他类型的文件...


                //对该路径下的 文件夹 进行遍历,获取文件夹
                string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
                foreach (string subdirectory in subdirectoryEntries)
                {
                    if (subdirectory.EndsWith(".gdb"))
                        list_ws.Add(ProcessFile(subdirectory));
                    else
                        ProcessDirectory(subdirectory);
                }
C#中,遍历文件夹读取其内容然后写入Excel通常会涉及`DirectoryInfo`, `FileInfo`, `Microsoft.Office.Interop.Excel`等命名空间。以下是概述的一个基本步骤: 1. 引入所需库: ```csharp using System.IO; using System.Linq; using Microsoft.Office.Interop.Excel; ``` 2. 定义目录路径、工作表进度条: ```csharp string dirPath = @"C:\YourFolderPath"; // 替换为你需要遍历文件夹路径 Excel.Application excelApp = new Excel.Application(); Workbook workbook = excelApp.Workbooks.Add(); Worksheet worksheet = workbook.ActiveSheet; IProgress<int> progress = new Progress<int>(percent => Console.WriteLine($"进度: {percent}%")); ``` 3. 使用递归函数遍历文件夹: ```csharp private void TraverseFolder(string path, int currentStep) { var directoryInfo = new DirectoryInfo(path); foreach (var fileInfo in directoryInfo.GetFiles()) { worksheet.Cells[currentStep + 1, 1] = fileInfo.FullName; // 文件路径 worksheet.Cells[currentStep + 1, 2] = fileInfo.Name; // 文件名 // 提高代码复用,你可以选择将这个插入操作放到一个单独的方法中 InsertRow(worksheet, currentStep + 1); ++currentStep; progress.Report(currentStep / directoryInfo.GetFiles().Length * 100); // 更新进度 } if (directoryInfo.GetDirectories().Any()) { TraverseFolder(directoryInfo.FullName, currentStep); } } ``` 4. 插入行方法(假设你需要自定义插入行的动作): ```csharp private void InsertRow(Worksheet ws, int row) { ws.Rows[row].Height = 15; // 可调整行高度 ws.Cells[row, 1].AutoFitColumn(); // 自动调整列宽 } ``` 5. 开始遍历并处理结束: ```csharp TraverseFolder(dirPath, 1); excelApp.Visible = true; // 显示Excel应用程序(如果需要) progress.Report(100); ``` 6. 关闭资源: ```csharp excelApp.Quit(); Marshal.ReleaseComObject(workbook); Marshal.ReleaseComObject(excelApp); ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值