3

Possible Duplicate:
How to recursively list all the files in a directory in C#?

How to scan all file in Folder and Subfolder?

Here is the code I have:

private void button1_Click(object sender, EventArgs e)
{
    folderBrowserDialog1.ShowDialog();
    label2.Text = folderBrowserDialog1.SelectedPath;
    viruses = 0;
    progressBar1.Value = 0;
    label1.Text+= viruses.ToString();
    listBox1.Items.Clear();
}

private void btnScan_Click_1(object sender, EventArgs e)
{

    List<string> search = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*").ToList();
    progressBar1.Maximum = search.Count;
    //foreach (Directory.GetDirectories.search))

    foreach(string item in search)
    {
        try
        {
            StreamReader stream = new StreamReader(item);
            string read = stream.ReadToEnd();
            foreach(string st in viruslist)
            {
                if(Regex.IsMatch(read,st));
                {
                    viruses+=1;
                    label1.Text+= listBox1.Items.Count;
                    listBox1.Items.Add(item);
                }
                progressBar1.Increment(1);
            }
        }
        catch(Exception ex)
        {
        }
    }
}

This code is scaning all files in root folder only, but not in subfolders. How to change this code so it can scan all files in folder and subfolder too?

Community
  • 1
  • 1
mapix
  • 43
  • 1
  • 2
  • 5
  • 1
    Please note that System.IO.File/Directory don't handle long paths - you may try Open Source Library http://zetalongpaths.codeplex.com/. There're commericial tools you may use if you don't want to reinvent the wheel; appliedalgo.com - – Swab.Jat Jan 02 '14 at 08:12
  • 1
    Sanning file by file using Regular Expression is a very computational intensive task! –  Jan 02 '14 at 08:23

4 Answers4

7

Since you are using the Directory class, just use the SearchOption parameter on your call to GetFiles as so:

Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*",SearchOption.AllDirectories).ToList();

Link to MSDN

Icarus
  • 63,293
  • 14
  • 100
  • 115
0

Pass SearchOption.AllDirectories to GetFiles().

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Please take a look at the SearchOption here http://msdn.microsoft.com/en-us/library/ms143448.aspx

That enables you to do: Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*",SearchOption.AllDirectories);

Jon
  • 38,814
  • 81
  • 233
  • 382
0

In the method Directory.GetFiles(...) you can provide a enum-value as third-parameter. The default here is just the top-directory. You can say to search in all subdirectories

Tomtom
  • 9,087
  • 7
  • 52
  • 95