當我們用Directory.GetFiles() 在特定路徑下尋找檔案時,
若不幸程式存取到系統資料夾時(列如: System Volume Information), 則程式可能中斷並跳出 UnauthorizedAccessException 的錯誤訊息
避免的方式很簡單,
建議先不要找檔案,先找資料夾
Directory.GetDirectories(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "*" ,SearchOption.TopDirectoryOnly);
過濾系統資料夾
if(d.Contains("System Volume Information"))continue;
if (new FileInfo(d).Attributes == FileAttributes.System) continue;
if (new FileInfo(d).Attributes == FileAttributes.Hidden) continue;
再去尋訪剩下的資料夾, 並找出指定的檔案 (SearchPattern )
fls = Directory.GetFiles(d, SearchPattern, SearchOption.AllDirectories);
將結果合併成一個List 並輸出
if (fls != null) files = files.Concat(fls).ToList<string>();
完整 Sample code 如下:
var dirs= Directory.GetDirectories(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "*" ,SearchOption.TopDirectoryOnly);
List<string> files = new List<string>();
foreach (string d in dirs)
{
if (d.Contains("System Volume Information")) continue;
if (new FileInfo(d).Attributes == FileAttributes.System) continue;
if (new FileInfo(d).Attributes == FileAttributes.Hidden) continue;
string[] fls = null;
try
{
fls = Directory.GetFiles(d, SearchPattern , SearchOption.AllDirectories);
if (fls != null) files = files.Concat(fls).ToList<string>();
}
catch (Exception ex)
{
}
}
|
留言
張貼留言