Sunday, July 8, 2012

c# - List all file names in a given folder

Use SearchOption.AllDirectories to list filenames from all directories if you have subdirectories in the given folder.

try
            {
                    string[] saFiles = Directory.GetFiles(ConfigurationSettings.AppSettings["INPUT_FOLDER_PATH"], "*.*", SearchOption.AllDirectories);

                    // Display all the files.

                    foreach (string file in saFiles)
                    {
                        using (StreamWriter writer = new StreamWriter(ConfigurationSettings.AppSettings["OUTPUT_FILE_NAME"],true))
                        {
                            writer.WriteLine(Path.GetFileNameWithoutExtension(file));
                        }
                        Console.WriteLine(Path.GetFileNameWithoutExtension(file));
                    }

            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

No comments: