How to list down all the files available in a directory using C#?


Firstly, use the DirectoryInfo object −

//creating a DirectoryInfo object
DirectoryInfo mydir = new DirectoryInfo(@"d:\amit");

Now, use the GetFiles() method to get all the files −

FileInfo [] f = mydir.GetFiles();

To get the list of files in a directory, try to run the following code −

Example

using System;
using System.IO;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         //creating a DirectoryInfo object
         DirectoryInfo mydir = new DirectoryInfo(@"d:\amit");

         // getting the files in the directory, their names and size
         FileInfo [] f = mydir.GetFiles();

         foreach (FileInfo file in f) {
            Console.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length);
         }
         Console.ReadKey();
      }
   }
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

285 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements