在C#中,遍历文件并处理异常时,可以使用try-catch
语句来捕获和处理可能发生的异常。以下是一个简单的示例,展示了如何使用try-catch
语句遍历文件夹并处理异常:
using System; using System.IO; class Program { static void Main() { string folderPath = @"C:\example_folder"; // 替换为你要遍历的文件夹路径 try { // 获取文件夹中的所有文件和子文件夹 DirectoryInfo directoryInfo = new DirectoryInfo(folderPath); DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(); FileSecurity fileSecurity = null; foreach (FileSystemInfo fileSystemInfo in directoryInfo.GetFileSystemInfos("*", SearchOption.AllDirectories)) { // 如果是文件,处理文件 if (fileSystemInfo is FileInfo) { FileInfo fileInfo = (FileInfo)fileSystemInfo; ProcessFile(fileInfo); } // 如果是文件夹,递归遍历子文件夹 else if (fileSystemInfo is DirectoryInfo) { DirectoryInfo subDirectoryInfo = (DirectoryInfo)fileSystemInfo; ProcessDirectory(subDirectoryInfo); } } } catch (Exception ex) { Console.WriteLine("An error occurred while processing the files: " + ex.Message); } } static void ProcessFile(FileInfo fileInfo) { try { // 在这里处理文件,例如读取文件内容、修改文件等 Console.WriteLine($"Processing file: {fileInfo.FullName}"); } catch (Exception ex) { Console.WriteLine($"An error occurred while processing the file '{fileInfo.FullName}': " + ex.Message); } } static void ProcessDirectory(DirectoryInfo directoryInfo) { try { // 遍历子文件夹 foreach (FileSystemInfo fileSystemInfo in directoryInfo.GetFileSystemInfos("*", SearchOption.AllDirectories)) { // 如果是文件,处理文件 if (fileSystemInfo is FileInfo) { FileInfo fileInfo = (FileInfo)fileSystemInfo; ProcessFile(fileInfo); } // 如果是文件夹,递归遍历子文件夹 else if (fileSystemInfo is DirectoryInfo) { DirectoryInfo subDirectoryInfo = (DirectoryInfo)fileSystemInfo; ProcessDirectory(subDirectoryInfo); } } } catch (Exception ex) { Console.WriteLine($"An error occurred while processing the directory '{directoryInfo.FullName}': " + ex.Message); } } }
在这个示例中,我们首先尝试获取指定文件夹中的所有文件和子文件夹。然后,我们使用try-catch
语句遍历这些文件和子文件夹,并在try
块中处理它们。如果在处理过程中发生异常,catch
块将捕获异常并输出错误信息。