Directory.GetFiles
方法在 C# 中用于獲取目錄中的所有文件。為了提高其穩(wěn)定性,你可以采取以下措施:
try-catch
語句來捕獲和處理可能發(fā)生的任何異常,如路徑不存在、權限問題等。string path = @"C:\Your\Directory\Path";
string[] files;
try
{
files = Directory.GetFiles(path);
}
catch (Exception ex)
{
// Handle the exception, log it, or rethrow it as a more specific exception
Console.WriteLine($"Error: {ex.Message}");
throw;
}
Directory.GetFiles
之前,確保提供的路徑是有效的。你可以使用 System.IO.Directory.Exists(path)
方法來檢查目錄是否存在。if (!Directory.Exists(path))
{
// Handle the error, e.g., create the directory or throw a specific exception
Console.WriteLine($"Directory does not exist: {path}");
throw new DirectoryNotFoundException($"Directory does not exist: {path}");
}
try-finally
語句可以在 finally
部分添加清理代碼。SearchOption.TopDirectoryOnly
選項來限制搜索深度,這可以提高性能并減少潛在的錯誤。files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);
Directory.GetFiles
可能會消耗大量內(nèi)存和時間。在這種情況下,考慮使用 Directory.EnumerateFiles
方法,它返回一個 IEnumerable<string>
,可以按需生成文件名,從而減少內(nèi)存占用。通過采取這些措施,你可以提高 Directory.GetFiles
方法的穩(wěn)定性和可靠性。