Collect all files and folders in a folder and the files and folders in the containing folders

If you are working with files and folders it's most of the time you will need the fill a treeview thing with files and folders. A recursive function easily fill the treeview.

  /// 
    /// Object wich hold a file or directory
    /// for use in a treeview
    /// 
    public class TreeViewLocation
    {
        public TreeViewLocation()
        {
            ChildLocations = new HashSet();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string FullName { get; set; }
        public ICollection ChildLocations { get; set; }
    }

And

/// 
    /// Object voor collecting all files and folders
    /// in a specified directory
    /// 
    public class TreeviewFileCollector
    {
        private List FoundFilesAndFolders = new List();

        public List FindFilesAndFolders(string folder)
        {
            if(string.IsNullOrEmpty(folder))
                throw new ArgumentNullException("Folder niet opgegeven!");
            
            if (!new System.IO.DirectoryInfo(folder).Exists)
                throw new ArgumentOutOfRangeException("Folder bestaat niet!");

            FindFiles(folder, null);
            
            return FoundFilesAndFolders;
                                
        }

        void FindFiles(string path, TreeViewLocation treeviewlocation )
          { 
              // get all files
                foreach(string file in Directory.GetFiles(path))
                {
                    if( treeviewlocation == null)
                        FoundFilesAndFolders.Add(new TreeViewLocation() { Name =  new FileInfo(file).Name, FullName = file });
                    else
                        treeviewlocation.ChildLocations.Add(new TreeViewLocation() { FullName = file, Name = new FileInfo(file).Name});
                }
               // get all directories
                foreach(string directory in Directory.GetDirectories(path))
                {
                    TreeViewLocation treeViewLocationDirectory = new TreeViewLocation();
                    treeViewLocationDirectory.FullName = directory;
                    treeViewLocationDirectory.Name = new DirectoryInfo(directory).Name;
                    if( treeviewlocation == null)
                        FoundFilesAndFolders.Add(treeViewLocationDirectory);
                    else
                        treeviewlocation.ChildLocations.Add(treeViewLocationDirectory);
                    FindFiles(directory, treeViewLocationDirectory);
                }
          }

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!