This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

10 Mar 2013

C# PROGRAM TO GET FILE NAMES IN A GIVEN DIRECTORY

C# PROGRAM TO GET FILE NAMES IN THE GIVEN DIRECTORY

original post


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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();
            }
        }

    }
}

Sample Output 1:


Sample Output 2:


No comments:

Post a Comment

Thanks for your comments.
-Sameer