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并捕获问题是,一旦其中一个目录被拒绝,程序就会停止。我希望它继续下一个目录。
例如,如果在filePaths中,我在10个目录中有450个文件,而在第二个目录中它被拒绝访问,则继续到下一个目录,依此类推。
答案 0 :(得分:2)
您需要抓住UnauthorizedAccessException
来电File.ReadAllText(...)
的{{1}}。绕过try/catch
中的读取操作,并在抛出异常时使用continue
关键字。您可以尝试check for accessibility ,但这可能不完全准确。
答案 1 :(得分:1)
很少有人建议
try.. catch
块中。如果指定的文件不可访问,则抛出Access-Denied Exception。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
}