File Searching using C#


To search files from 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();
      }
   }
}

Above, we have firstly added the directory wherein we want to find the files −

DirectoryInfo mydir = new DirectoryInfo(@"d:\amit");

Then read the file −

FileInfo [] f = mydir.GetFiles();

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

The following is the output −

FileName: Info.txt: Size: 2kb
File Name: New.html: Size: 10kb

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

460 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements