Pages

Monday, 29 January 2018

C# PROGRAM TO GET FILE NAMES IN A GIVEN DIRECTORY

C# PROGRAM TO GET FILE NAMES IN A GIVEN DIRECTORY
using System;
using System.IO;

namespace GetFileNames
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string FolderPath ;
                string[] Files;
                Console.WriteLine(" Enter the Directory Path to get File Names in it : ");
                FolderPath=Console.ReadLine();
                Files = Directory.GetFiles(FolderPath);
                Console.WriteLine("\n The FileNames with extension in given Directory are : \n\n");
              
                foreach (string FileName in Files)
                {
                    // Create the FileInfo object only when needed to ensure
                    // the information is as current as possible.
                    System.IO.FileInfo fi = null;
                    try
                    {
                        fi = new System.IO.FileInfo(FileName);
                    }
                    catch (System.IO.FileNotFoundException ex)
                    {
                        // To inform the user and continue is
                        // sufficient for this demonstration.
                        // Your application may require different behavior.
                        Console.WriteLine(ex.Message);
                        continue;
                    }
                    Console.WriteLine("{0}", fi.Name);
                   // Console.WriteLine("{0}", fi.Directory);  //prints filepath
                   // Console.WriteLine("{0}", fi.DirectoryName); // prints directorypath
                }
                Console.ReadLine();
            }
            catch (DirectoryNotFoundException ex)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.WriteLine("\n\n Directory Not Found..Press any key to exit...");
                Console.ReadKey();
            }
        }

    }

}