如何在C#中实现动态路径查找并删除指定文件夹?
实现遍历全系统查找并清理指定路径文件夹的C#代码
以下是修改后的代码,实现遍历全计算机查找路径为\A\B的文件夹,清理并删除该文件夹,同时处理访问权限异常:
using System; using System.IO; class FolderCleaner { // 清理指定文件夹(排除指定文件/文件夹) private static void ClearFolderWithFilter(string folderName, string filesToExclude = "debug.log") { DirectoryInfo dir = new DirectoryInfo(folderName); // 跳过不存在的文件夹 if (!dir.Exists) return; try { // 删除符合条件的文件 foreach (FileInfo fi in dir.GetFiles()) { if (!fi.Name.Contains(filesToExclude)) { try { fi.Delete(); } catch (UnauthorizedAccessException) { Console.WriteLine($"无权限删除文件: {fi.FullName}"); } catch (IOException ex) { Console.WriteLine($"删除文件出错: {fi.FullName}, 错误信息: {ex.Message}"); } } } // 递归清理并删除子文件夹 foreach (DirectoryInfo di in dir.GetDirectories()) { if (!di.Name.Contains(filesToExclude)) { ClearFolderWithFilter(di.FullName, filesToExclude); try { di.Delete(); } catch (UnauthorizedAccessException) { Console.WriteLine($"无权限删除文件夹: {di.FullName}"); } catch (IOException ex) { Console.WriteLine($"删除文件夹出错: {di.FullName}, 错误信息: {ex.Message}"); } } } // 清理完成后删除当前文件夹 try { dir.Delete(); Console.WriteLine($"已删除文件夹: {folderName}"); } catch (UnauthorizedAccessException) { Console.WriteLine($"无权限删除文件夹: {folderName}"); } catch (IOException ex) { Console.WriteLine($"删除文件夹出错: {folderName}, 错误信息: {ex.Message}"); } } catch (UnauthorizedAccessException) { Console.WriteLine($"无权限访问文件夹: {folderName}"); } catch (Exception ex) { Console.WriteLine($"处理文件夹出错: {folderName}, 错误信息: {ex.Message}"); } } // 遍历全系统查找并清理所有\A\B文件夹 public static void FindAndClearAllABFolders(string filesToExclude = "debug.log") { // 获取计算机上所有驱动器 DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives) { // 跳过未就绪的驱动器(比如光驱) if (!drive.IsReady) continue; try { // 在当前驱动器下递归搜索\A\B文件夹 SearchForABFolder(drive.RootDirectory.FullName, filesToExclude); } catch (UnauthorizedAccessException) { Console.WriteLine($"无权限访问驱动器: {drive.Name}"); } catch (Exception ex) { Console.WriteLine($"处理驱动器出错: {drive.Name}, 错误信息: {ex.Message}"); } } } // 递归搜索指定根目录下的\A\B文件夹 private static void SearchForABFolder(string rootPath, string filesToExclude) { try { // 遍历当前目录下的所有子文件夹 foreach (string dirPath in Directory.GetDirectories(rootPath)) { // 检查当前文件夹是否是目标\A\B(即路径以\A\B结尾) if (dirPath.EndsWith(@"\A\B", StringComparison.OrdinalIgnoreCase)) { ClearFolderWithFilter(dirPath, filesToExclude); } else { // 递归搜索更深层级的文件夹 SearchForABFolder(dirPath, filesToExclude); } } } catch (UnauthorizedAccessException) { Console.WriteLine($"无权限访问目录: {rootPath}"); } catch (Exception ex) { Console.WriteLine($"搜索目录出错: {rootPath}, 错误信息: {ex.Message}"); } } // 示例调用 static void Main() { FindAndClearAllABFolders(); } }
关键修改说明
- 全系统遍历:通过
DriveInfo.GetDrives()获取所有可用驱动器,逐个递归搜索目标文件夹\A\B - 权限异常处理:在文件/文件夹操作的关键位置添加
try-catch,捕获UnauthorizedAccessException和IOException,避免程序崩溃并输出提示信息 - 目标文件夹匹配:通过路径结尾匹配
\A\B,确保找到所有符合路径结构的文件夹 - 安全清理逻辑:先清理文件夹内的文件和子文件夹,最后删除目标文件夹,全程保留排除项(
debug.log相关文件/文件夹)
内容的提问来源于stack exchange,提问作者Yogesh Bhosale
相关产品推荐
相关产品推荐

