公司动态

C#遍历硬盘文件全攻略

📅 2026/7/23 4:53:00
C#遍历硬盘文件全攻略
核心实现方案使用 C# 读取电脑各盘文件主要依赖System.IO命名空间下的DriveInfo、Directory和File类。核心逻辑分为三步获取所有驱动器、遍历目录树、读取文件内容或属性。需注意处理权限异常如系统盘受限及特殊文件夹如回收站。1. 完整代码示例以下代码实现了遍历本地所有磁盘跳过受保护的目录并读取指定类型文件以.txt为例的内容及基本信息。using System; using System.IO; using System.Collections.Generic; namespace DiskFileReader { class Program { static void Main(string[] args) { // 获取所有逻辑驱动器 DriveInfo[] drives DriveInfo.GetDrives(); Console.WriteLine(开始扫描本地磁盘... ); foreach (DriveInfo drive in drives) { // 仅处理已就绪的驱动器避免访问光驱无光盘时报错 if (!drive.IsReady) { Console.WriteLine($驱动器 {drive.Name} 未就绪跳过。); continue; } Console.WriteLine($正在扫描驱动器{drive.Name} ({drive.DriveFormat})); try { // 递归遍历根目录 TraverseDirectory(drive.RootDirectory.FullName, 0); } catch (UnauthorizedAccessException ex) { // 捕获根目录无权访问异常常见于系统盘 Console.WriteLine($无法访问 {drive.Name} 根目录{ex.Message}); } catch (Exception ex) { Console.WriteLine($扫描 {drive.Name} 时发生未知错误{ex.Message}); } } Console.WriteLine( 扫描完成。按任意键退出...); Console.ReadKey(); } /// summary /// 递归遍历目录并读取文件 /// /summary /// param namepath当前目录路径/param /// param namedepth当前目录深度用于控制缩进显示/param private static void TraverseDirectory(string path, int depth) { // 限制递归深度防止死循环或栈溢出可选 if (depth 10) return; string indent new string( , depth * 2); try { // 1. 获取当前目录下所有子目录 string[] directories Directory.GetDirectories(path); foreach (string dir in directories) { // 跳过系统关键目录以减少报错和提升速度 if (IsSystemFolder(dir)) continue; try { TraverseDirectory(dir, depth 1); } catch (UnauthorizedAccessException) { // 忽略无权限的子目录 } catch (PathTooLongException) { // 忽略路径过长的目录 } } // 2. 获取当前目录下所有文件 string[] files Directory.GetFiles(path); foreach (string file in files) { try { ReadFileContent(file, indent); } catch (UnauthorizedAccessException) { // 忽略无权限的文件 } catch (IOException) { // 忽略被占用或损坏的文件 } } } catch (UnauthorizedAccessException) { // 当前目录本身无权访问 } catch (PathTooLongException) { // 路径过长 } } /// summary /// 读取并打印文件信息 /// /summary private static void ReadFileContent(string filePath, string indent) { FileInfo fileInfo new FileInfo(filePath); // 示例仅读取小于 1MB 的文本文件内容防止大文件卡死 if (fileInfo.Extension.ToLower() .txt fileInfo.Length 1024 * 1024) { // 使用 StreamReader 读取文件内容 using (StreamReader reader new StreamReader(filePath)) { string firstLine reader.ReadLine(); Console.WriteLine(${indent}[文件] {fileInfo.Name} | 大小{fileInfo.Length} bytes | 首行{firstLine ?? (空)}); } } else { // 非目标文件或大文件仅显示属性 Console.WriteLine(${indent}[文件] {fileInfo.Name} | 大小{fileInfo.Length} bytes); } } /// summary /// 判断是否为需要跳过的系统文件夹 /// /summary private static bool IsSystemFolder(string path) { string lowerPath path.ToLower(); // 跳过回收站、系统卷信息、Windows 系统目录等 return lowerPath.Contains($recycle.bin) || lowerPath.Contains(system volume information) || lowerPath.Contains(windows\winsxs) || lowerPath.Contains(program files); } } }2. 关键技术点解析技术环节核心类/方法作用与注意事项参考来源获取磁盘DriveInfo.GetDrives()返回计算机上所有逻辑驱动器的数组。需检查IsReady属性防止访问无光盘的光驱引发异常。目录遍历Directory.GetDirectories()Directory.GetFiles()分别获取子目录和文件列表。必须包裹在try-catch中处理UnauthorizedAccessException因为普通用户无权访问某些系统目录。文件读取StreamReader/File.ReadAllText()StreamReader适合逐行读取大文件流式处理节省内存File.ReadAllText适合小文件一次性读取。需注意文件编码问题。异常处理UnauthorizedAccessExceptionPathTooLongException遍历全盘时极大概率遇到权限不足或路径超长260 字符的情况必须显式捕获并跳过否则程序会崩溃。远程扩展ManagementObjectSearcher(WMI)若需读取远端电脑文件需使用 WMI (Windows Management Instrumentation) 技术通过ManagementScope建立连接。3. 常见问题与解决方案权限拒绝 (0x80004005 / UnauthorizedAccessException)现象访问 C 盘根目录或Program Files时报错。原因当前运行进程权限不足或文件系统限制了访问 。对策代码中必须使用try-catch忽略特定目录的错误若需强制访问需以“管理员身份”运行编译后的 exe 程序。路径过长 (PathTooLongException)现象深层嵌套目录导致路径超过 260 个字符。对策在 .NET Framework 4.6.2 或 .NET Core 中可在app.config中启用长路径支持 (runtimeAppContextSwitchOverrides valueSwitch.System.IO.UseLegacyPathHandlingfalse //runtime)或在代码中捕获该异常直接跳过。文件占用 (IOException)现象读取正在被其他程序独占锁定的文件。 *对策使用FileStream打开时指定FileShare.ReadWrite模式或直接捕获IOException跳过该文件。4. 进阶场景读取特定格式文件若需读取 Excel 等非纯文本文件需引入第三方库如 NPOI不能直接使用StreamReader。// 伪代码示例使用 NPOI 读取 Excel // 需先通过 NuGet 安装 NPOI 包 /* using NPOI.XSSF.UserModel; using NPOI.SS.UserModel; public void ReadExcel(string filePath) { using (FileStream fs new FileStream(filePath, FileMode.Open, FileAccess.Read)) { IWorkbook workbook new XSSFWorkbook(fs); // 读取 .xlsx ISheet sheet workbook.GetSheetAt(0); IRow row sheet.GetRow(0); Console.WriteLine(row.GetCell(0).StringCellValue); } } */参考来源异常System.ComponentModel.Win32Exception (0x80004005)【已解决】PLC读取PC文件汇川PLC读取电脑上的文件C# 目录路径操作和读取文件详解C#如何用NPOI创建、读取、更新Excel文件C#读取远端电脑文件的方法