Loading ...

List all the files of a particular extension in a directory,c# | CodeAsp.Net

List all the files of a particular extension in a directory

 /5
0 (0votes)

 

Yesterday, I saw a person posted a question on forums "How to get list of files having .txt extension inside a directory with c#". I thought I should blog for it. I decided to write a generic method which can be used for any extension. So I made a sample project to demonstrate the same. I have used FileInfo and DirectoryInfo class to achieve it. Below is the sample code:

 

#region Using Directives

using System;
using System.IO;

#endregion

public class Example
{
    const string DesiredExtension = "*.txt";
    const string DirectoryPath = @"C:\DummyFolder";

    public static void Main()
    {
        foreach (var info in GetFiles(DirectoryPath, DesiredExtension))
        {
            Console.WriteLine(info.Name);
        }
        Console.ReadLine();
    }

    public static FileInfo[] GetFiles(string directoryPath, string desiredExtension)
    {
        var directoryInfo = new DirectoryInfo(directoryPath);
        return directoryInfo.GetFiles(desiredExtension);
    }
}


Explanation of code:

I made a generic method named “GetFiles” which will accept two parameters , first one is directoryPath second one is desiredExtension. The directoryPath is that path of directory of which you want to get the files and the desiredExtension is the extension of files which you need to list (like “*.txt” ,”*.jpg”,”*.rar” ). This method will return FileInfo type collection.

 

public static FileInfo[] GetFiles(string directoryPath, string desiredExtension)

    {

        var directoryInfo = new DirectoryInfo(directoryPath);

        return directoryInfo.GetFiles(desiredExtension);

    }


Next I simply put a foreach on the returned collection to list out the names

 

foreach (var info in GetFiles(DirectoryPath, DesiredExtension))

        {

            Console.WriteLine(info.Name);

        }

 

Do let me know your feedback,comments.

 

Comments (no comments yet)

Top Posts