List of files (from current and all sub directories)

Mitja Bonca 0 Tallied Votes 1K Views Share

The code gets all the files (only names, if you want to get the paths too, simply remove for loop (its only one) from the code. Files are stored into a generic list.

Mitja

class Program
    {
        static void Main(string[] args)
        {
            List<string> allFiles = GettingFiles(@"C:\1");
        }

        public static List<string> GettingFiles(string path)
        {
            List<string> listFiles = new List<string>();

            //1. get files from the current directory:
            string[] currentFiles = Directory.GetFiles(path, "*.*");
            foreach (string file in currentFiles)
                listFiles.Add(file);

            //2. get files from other sub directories:
            string[] directories = Directory.GetDirectories(path);
            foreach (string dir in directories)
            {
                string[] files = GetFilesFromDirectory(dir);
                listFiles.AddRange(files);
            }

            //for the end, lets get only the names of the files (remove the path):
            for (int i = 0; i < listFiles.Count; i++)
            {
                string fileName = Path.GetFileName(listFiles[i]);
                listFiles[i] = fileName;
            }
            return listFiles;
        }

        private static string[] GetFilesFromDirectory(string path)
        {
            string[] files = Directory.GetFiles(path);
            return files;
        }
    }
ShahanDev 41 Junior Poster

Hi!

Thanks for sharing it.

I wanna share one thing that, is this not good if you include directories and sub-directories in one statements ??? like this: (part of your code)

//1. get files from the current directory:
            string[] currentFiles = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly | SearchOption.AllDirectories);
            foreach (string file in currentFiles)
                listFiles.Add(file);
ShahanDev 41 Junior Poster

Or further compact it this way:

//1. get files from the current directory:
listFiles.AddRange(Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly | SearchOption.AllDirectories));

Note: I just want a discussion not pin pointing your code in a wrong manner.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.