Use Directory.getFiles () to traverse the directory safely
Challenge
Recursive solution
Explore the directory structure with this code, ignore the irreplaceable folder and continue to process the accessable files. You can customize the CATCH block to swallow abnormality or perform custom processing, such as recording it. The improved code contains a
<code class="language-csharp">using System; using System.IO; public static class Program { public static void Main() { string path = ""; // 获取目录路径 ProcessAllFiles(path, ProcessFile); } private static void ProcessFile(string path) { /* 在此处添加文件处理代码。 */ } private static void ProcessAllFiles(string folder, Action<string> fileAction) { try { foreach (string file in Directory.GetFiles(folder)) { fileAction(file); } foreach (string subDir in Directory.GetDirectories(folder)) { ProcessAllFiles(subDir, fileAction); } } catch (Exception ex) { // 处理或忽略异常(例如,将其记录下来以便日后查看)。 考虑记录异常类型和路径信息。 Console.WriteLine($"Error processing directory '{folder}': {ex.Message}"); } } }</code>
try-catch
Conclusion
The above is the detailed content of How Can I Safely Process Files in a Directory Structure While Ignoring Access Denied Exceptions in C#?. For more information, please follow other related articles on the PHP Chinese website!