![](/img/trans.png)
[英]System.UnauthorizedAccess Exception: Access to the path c:\\ is denied
[英]How to ignore “Access to the path is denied” / UnauthorizedAccess Exception in C#?
如何繞過/忽略 “拒絕訪問路徑” / UnauthorizedAccess異常
並繼續使用此方法收集文件名;
public static string[] GetFilesAndFoldersCMethod(string path)
{
string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
return filenames;
}
//正在呼叫...
foreach (var s in GetFilesAndFoldersCMethod(@"C:/"))
{
Console.WriteLine(s);
}
我的應用程序在GetFilesAndFoldersCMethod的第一行停止,並且出現異常; “拒絕訪問路徑'C:\\ @ Logs \\'。”。 請幫我...
謝謝,
最好的方法是添加一個Try / Catch塊來處理異常...
try
{
string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
return filenames;
}
catch (Exception ex)
{
//Do something when you dont have access
return null;//if you return null remember to handle it in calling code
}
如果您正在此函數中執行其他代碼,並且還想確保它是導致其失敗的訪問異常(此異常由Directory.GetFiles函數拋出),則還可以專門處理UnauthorizedAccessException 。
try
{
//...
}
catch(UnauthorizedAccessException ex)
{
//User cannot access directory
}
catch(Exception ex)
{
//a different exception
}
編輯 :正如在下面的注釋中指出的那樣,您似乎正在使用GetFiles函數調用進行遞歸搜索。 如果您希望它繞過任何錯誤並繼續進行,那么您將需要編寫自己的遞歸函數。 這里有一個很好的例子 ,它將滿足您的需求。 這是您所需要的修改。
List<string> DirSearch(string sDir)
{
List<string> files = new List<string>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return files;
}
看一下c#編程指南中的這篇文章:
基於MS頁面以及在此處關於stackoverflow的各種嘗試,我有一個似乎可行的解決方案,並且避免了所有GetFiles()/ GetDirectories()異常。
cf https://stackoverflow.com/a/10728792/89584
(原始問題可能被視為與此問題的重復,反之亦然)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.