Wednesday, December 20, 2017

Select all files inside a directory/folder (c# / .NET)


The below function implements the inbuilt libraries in .net to get all possible files inside a folder/directory. No matter how many number of folders or child folders it contains, it searches all the folders and returns a list of all file paths. It is a recursive function and hence can be a good example for the beginners to understand how recursive function works. 

        // Returns List of file paths for given search directory path.
        public List<String> SearchFiles(string searchDirectoryPath)
        {
            try
            {
                //declaration of list of full filepaths
                List<String> fileList = new List<String>();

                // fetch all files in the directory
                foreach (string file in Directory.GetFiles(searchDirectoryPath))
                {
                    fileList.Add(file);
                }

                // recursive function call for other directories inside of the current directory
                foreach (string directory in Directory.GetDirectories(searchDirectoryPath))
                {
                    fileList.AddRange(SearchFiles(directory));
                }

                //return the list of filepaths
                return fileList;
            }
            catch (Exception ex)
            {
                // throws exception if caught
                throw ex;
            }
        }


Call this function to get list of full file paths like below :


var allFiles = SearchFiles(@"D:\YourFolder");

Note : You will need  System.IO to use Directory class.

No comments:

Post a Comment