![](/img/trans.png)
[英]How can i check also sub directories and/or files for access denied and to pas over if access denied?
[英]How can i check for access denied when getting files?
private void DirSearch(string root, string filesExtension,string textToSearch, BackgroundWorker worker, DoWorkEventArgs e)
{
string[] filePaths = null;
int numberoffiles = 0;
int numberofdirs = 0;
try
{
filePaths = Directory.GetFiles(root, filesExtension, SearchOption.AllDirectories);
}
catch(Exception err)
{
string ad = err.ToString();
}
if (filePaths != null && filePaths.Length > 0)
{
for (int i = 0; i < filePaths.Length; i++)
{
_busy.WaitOne();
if (worker.CancellationPending == true)
{
e.Cancel = true;
return;
}
List<MyProgress> prog = new List<MyProgress>();
int var = File.ReadAllText(filePaths[i]).Contains(textToSearch) ? 1 : 0;
if (var == 1)
{
string filename = filePaths[i];//filePaths[i].Split('\\').Last();
numberoffiles++;
prog.Add(new MyProgress { Report1 = filename, Report2 = numberoffiles.ToString() });
backgroundWorker1.ReportProgress(0, prog);
Thread.Sleep(100);
}
numberofdirs++;
label1.Invoke((MethodInvoker)delegate
{
label1.Text = numberofdirs.ToString();
label1.Visible = true;
});
Thread.Sleep(100);
}
}
}
我正在使用try and catch的問題是,一旦目錄之一被拒絕訪問,程序就會停止。 我希望它繼續到下一個目錄。
例如,如果在filePaths中,我在10個目錄中有450個文件,而在第二個目錄中則拒絕訪問,則繼續到下一個目錄,依此類推。
您將需要捕獲File.ReadAllText(...)
調用正在發出的UnauthorizedAccessException
。 將讀取操作括在try/catch
並在引發異常時使用continue
關鍵字。 您可以嘗試檢查可訪問性 ,但這可能並不完全准確。
給你的建議很少
try.. catch
塊內。 因此,如果指定的文件不可訪問,將引發訪問拒絕異常。 restrictedFiles
跟蹤跳過的文件。 continue;
趕上繼續迭代。 為了更好的理解,讓我重命名變量。 現在考慮代碼
void DirSearch(string rootDirectory, string filesExtension, string textToSearch, BackgroundWorker worker, DoWorkEventArgs e)
{
List<string> filePathList = new List<string>();
List<string> restrictedFiles = new List<string>();
// Other Inits
try
{
filePathList = Directory.GetFiles(rootDirectory, filesExtension, SearchOption.AllDirectories).ToList();
}
catch (Exception err)
{
string ad = err.ToString();
}
foreach (string file in filePathList)
{
try
{
// Code before
int var = File.ReadAllText(file).Contains(textToSearch) ? 1 : 0;
// it will throw exception if it is not accessible
// Your code after
}
catch (Exception)
{
restrictedFiles.Add(file);
continue;
}
}
// restrictedFiles will contains all restricted files @ the end of iteration
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.