0

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;
        }
    }
2
Contributors
2
Replies
9
Views
6 Years
Discussion Span
Last Post by ShahanDev
0

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);
0

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.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.