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和catch的問題是,一旦一個目錄被訪問被拒絕,程序就停止。我希望它繼續到下一個目錄。如何在獲取文件時檢查訪問被拒絕?
如果在filePaths中,例如,我在10個目錄中有450個文件,在第二個目錄中它的訪問被拒絕,然後繼續到下一個目錄等等。
什麼是睡眠()?如果你打算使用BackgroundWorker,那麼慣例是使用ReportProgress()而不是Invoke() – MickyD