3

I want to display all the files from a selected folder.. ie files from that folder and files from the subfolders which are in that selected folder.

example -

I have selected D:\Eg. Now I have some txt and pdf files in that. Also I have subfolders in that which also contain some pdf files. Now I want to display all those files in a data grid.

My code is

public void  selectfolders(string filename)
{      
     FileInfo_Class fclass;
     dirInfo = new DirectoryInfo(filename);

     FileInfo[] info = dirInfo.GetFiles("*.*");
     foreach (FileInfo f in info)
     {

        fclass = new FileInfo_Class();
        fclass.Name = f.Name;
        fclass.length = Convert.ToUInt32(f.Length);
        fclass.DirectoryName = f.DirectoryName;
        fclass.FullName = f.FullName;
        fclass.Extension = f.Extension;

        obcinfo.Add(fclass);  
     }
     dataGrid1.DataContext = obcinfo;
} 

What to do now?

nrofis
  • 8,975
  • 14
  • 58
  • 113
omkar patade
  • 1,442
  • 9
  • 34
  • 66
  • You might also find this question useful: http://stackoverflow.com/questions/929276/how-to-recursively-list-all-the-files-in-a-directory-in-c – dash Oct 19 '12 at 12:11

2 Answers2

14

Just use

FileInfo[] info = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);

which will handle the recursion for you.

Rawling
  • 49,248
  • 7
  • 89
  • 127
8

You should recursively select files from all subfolders.

public void  selectfolders(string filename)
{
    FileInfo_Class fclass;
    DirectoryInfo dirInfo = new DirectoryInfo(filename);

    FileInfo[] info = dirInfo.GetFiles("*.*");
    foreach (FileInfo f in info)
    {
        fclass = new FileInfo_Class();
        fclass.Name = f.Name;
        fclass.length = Convert.ToUInt32(f.Length);
        fclass.DirectoryName = f.DirectoryName;
        fclass.FullName = f.FullName;
        fclass.Extension = f.Extension;
        obcinfo.Add(fclass);
    }
    DirectoryInfo[] subDirectories = dirInfo.GetDirectories();
    foreach(DirectoryInfo directory in subDirectories)
    {
        selectfolders(directory.FullName);
    }
}
luvieere
  • 37,065
  • 18
  • 127
  • 179
Dmitrii Dovgopolyi
  • 6,231
  • 2
  • 27
  • 44