在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
塊將捕獲異常并輸出錯誤信息。