Elegantly handle file and folder permission issues in Directory.GetFiles()
When using Directory.GetFiles()
to enumerate files in a directory, you may encounter obstacles if you encounter a protected folder or file. This may cause the file listing process to stop suddenly with an exception. But what if you want to gracefully ignore these restrictions and continue traversing the accessible files?
The key is to abandon the AllDirectories
parameters and handle the recursion manually. By checking each subdirectory individually, you can have more granular control over the process.
Consider the following code snippet:
<code class="language-csharp">using System; using System.IO; static class Program { static void Main() { string path = ""; // TODO ApplyAllFiles(path, ProcessFile); } static void ProcessFile(string path) {/* ... */} static void ApplyAllFiles(string folder, Action<string> fileAction) { try { foreach (string file in Directory.GetFiles(folder)) { fileAction(file); } } catch (UnauthorizedAccessException) { // 处理异常 } catch (Exception ex) { // 处理其他异常 } foreach (string subDir in Directory.GetDirectories(folder)) { try { ApplyAllFiles(subDir, fileAction); } catch (UnauthorizedAccessException) { // 处理异常,例如记录错误信息或忽略 } catch (Exception ex) { // 处理其他潜在异常 } } } }</code>
In this code, we use a delegate (Action<string>
) to specify the action to be performed on each file found. The ApplyAllFiles()
method recursively explores subdirectories, capturing any UnauthorizedAccessException
and continuing its exploration.
By manually managing recursion, you can effectively bypass inaccessible folders or files, ensuring only authorized items are processed without interrupting your file list operations. The improved code also handles exceptions for Directory.GetFiles
to ensure a more robust program.
The above is the detailed content of How Can I Ignore Permission Errors When Using Directory.GetFiles()?. For more information, please follow other related articles on the PHP Chinese website!