简体   繁体   中英

Why when getting directories and files recursive it's adding to the List<string> only directories and not files?

In dowork event

DirSearch(textBox3.Text, textBox2.Text, textBox1.Text, worker, e);

textbox3 text contains the root directory. textbox2 text contaons the extension to search for in this case CS and textbox1 text contains the text to search inside each file.

The DirSearch method

void DirSearch(string rootDirectory, string filesExtension, string textToSearch, BackgroundWorker worker, DoWorkEventArgs e)
        {
            List<string> filePathList = new List<string>();
            List<string> restrictedFiles = new List<string>();
            int overallfiles = 0;
            int numberoffiles = 0;
            int numberofdirs = 0;

            try
            {
                filePathList = SearchAccessibleFilesNoDistinct(rootDirectory, null).ToList();
            }
            catch (Exception err)
            {
                string ad = err.ToString();
            }
            foreach (string file in filePathList)
            {
                try
                {
                    _busy.WaitOne();
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        return;
                    }
                    List<MyProgress> prog = new List<MyProgress>();
                    int var = File.ReadAllText(file).Contains(textToSearch) ? 1 : 0;

                    overallfiles++;
                    if (var == 1)
                    {
                        numberoffiles++;
                        prog.Add(new MyProgress { Report1 = file, Report2 = numberoffiles.ToString() });
                        backgroundWorker1.ReportProgress(0, prog);
                    }
                    numberofdirs++;
                    label1.Invoke((MethodInvoker)delegate
                    {
                        label1.Text = numberofdirs.ToString();
                        label1.Visible = true;
                    });
                }
                catch (Exception)
                {
                    restrictedFiles.Add(file);
                    continue;
                }
            }

        }

And inside the DirSearch method i'm calling the method SearchAccessibleFilesNoDistinct and in this method i have the problem.

IEnumerable<string> SearchAccessibleFilesNoDistinct(string root, List<string> files)
        {
            if (files == null)
                files = new List<string>();
            if (Directory.Exists(root))
            {
                foreach (var file in Directory.EnumerateFiles(root))
                {
                    string ext = Path.GetExtension(file);
                    if (!files.Contains(file) && ext == textBox2.Text)
                    {
                        files.Add(file);
                    }
                }
                foreach (var subDir in Directory.EnumerateDirectories(root))
                {
                    try
                    {
                        SearchAccessibleFilesNoDistinct(subDir, files);
                        files.Add(subDir);
                    }
                    catch (UnauthorizedAccessException ex)
                    {

                    }
                }
            }
            return files;
        }

For some reaosn in the end i see in the List files only directories and not files at all.

Then in the DirSearch when it's trying to search in files it's making exception since there are no files only directories.

I checked now and found that in the method SearchAccessibleFilesNoDistinct the problem started after i added this part that check for extension:

string ext = Path.GetExtension(file);
if (!files.Contains(file) && ext == textBox2.Text)

If i remove the part:

&& ext == textBox2.Text

So the if will be:

if (!files.Contains(file))

Then it will work it will add all the files to the List files. But once i added this extension checking it's adding only directories to files. And not files at all.

Not sure this whole method SearchAccessibleFilesNoDistinct something with the recursive is not working fine.

When using break point on top of the method i see root directory is root = "d:\\C-Sharp" and the List is null.

Then it should start the whole operation.

I think you can write it shorter (call it inside Task.Factory.StartNew to make it async), just quick and dirty sample:

var directory = @"D:\Downloads";
var extension = @"*.txt";
var textToSearch = @"abc";
var files = SearchFiles(directory, extension, SearchOption.AllDirectories);
...
private static List<string> SearchFiles(string directory, string extension, string textToSearch)
{
  var results = new List<string>();
  var files = Directory.GetFiles(directory, extension, SearchOption.AllDirectories);
  foreach (var file in files)
  {
    var content = File.ReadAllText(file);
    if (content.Contains(textToSearch))
    {
      results.Add(file);
    }
  }
  return results;
}

The value of textBox2.Text is cs (small letters)

You got the extension of file using Path.GetExtension method. The method returns the extension of the specified path including the period ".". So you should type .cs in your text box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM