![](/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.