Monday, July 19, 2010

List All Files / Folders in Folder

To output all files and folders which are contained in a specific folder we use the C# class System.IO.DirectoryInfo.
This is initialized with the wanted folder and then provides 2 functions to output the folder content: GetFiles() and GetDirectories(). The first one returns an array of System.IO.FileInfo objects, which represent all files in that folder.
The second one returns an array of the type System.IO.DirectoryInfo, which contains all subfolders of the folder.
The following sample application prints all files and subfolders of the directory"C:\testfolder" in the console:

            System.IO.DirectoryInfo ParentDirectory = new System.IO.DirectoryInfo("C:\\testfolder");

            foreach (System.IO.FileInfo f in ParentDirectory.GetFiles())
            {
                Console.WriteLine("File: " + f.Name);
            }

            foreach (System.IO.DirectoryInfo d in ParentDirectory.GetDirectories())
            {
                Console.WriteLine("Folder: " + d.Name);
            }

On Udo's Blog there is further a little extension explaining how to list recursively also files from subdirectories.

No comments:

Post a Comment