Click here to Skip to main content
11,720,321 members (82,224 online)
Click here to Skip to main content

Get File Names of a Particular File Type using LINQ

, 26 Feb 2014 CPOL 13.8K 16
Rate this:
Please Sign up or sign in to vote.
This is a simple Trick to find File Names of a particular File Type existing in a Folder.

This is a simple Trick to find File Names of a particular File Type existing in a Folder.

Background

Suppose, you want to find the File Names of the CSV Files in a folder. So, you need to exclude all other files and consider the CSV Files only. This was implemented in one of my projects, where all the CSV File Names from a folder got populated in a DropDownList.

Let’s Explore

So, the main thing here is to find a particular type of File. For that, I used the following code.

DirectoryInfo di = new DirectoryInfo(folderPath);

// Get only the CSV files.
List<string> csvFiles = di.GetFiles("*.csv")
                          .Where(file => file.Name.EndsWith(".csv"))
                          .Select(file => file.Name).ToList();

Here I have used DirectoryInfo.GetFiles Method (String)

Returns a file list from the current directory matching the given search pattern.

So, di.GetFiles(“*.csv”) would give us a list of all the CSV Files in that folder.

  • Here *.csv is the SearchPattern and * means any string before .csv
  • Now, Where Clause is used to make sure that File Extension Ends With .csv and nothing else. 

Then, we are selecting the File Names by Select clause like Select(file => file.Name)

Note 

You can apply this Trick to find any File Type. You just need to change the SearchPattern accordingly. If you wish to find pdf files, then it would be di.GetFiles("*.pdf").

Full Code

I have used another Where condition here as per the requirements to exclude the CSV Files, having _something in their File Names.

/// <summary>
/// This function Populates CSV File Names on a DropDownList.
/// </summary>
private void PopulateCSVFilesDropDownList()
{
    try
    {
        string folderPath = GetFolderPath();

        if (!string.IsNullOrEmpty(folderPath))
        {
            if (Directory.Exists(folderPath))
            {
                DirectoryInfo di = new DirectoryInfo(folderPath);

                // Get only the CSV files excluding the ones having 
                // "_something" appended to them.
                List<string> csvFiles = di.GetFiles("*.csv")
                                          .Where(file => file.Name.EndsWith(".csv") &&
                                                         !file.Name.Contains("_something"))
                                          .Select(file => file.Name).ToList();

                // Bind the DropDown and add one default option at the top.
                ddlCSVFiles.DataSource = csvFiles;
                ddlCSVFiles.DataBind();
                ddlCSVFiles.Items.Insert(0, new ListItem("Please select a file", "-1"));
            }
            else
            {
                // DropDownList is hided and Error message is displayed.
                ddlCSVFiles.Visible = false;
                lblErrorMessage.Visible = true;
                lblErrorMessage.Text = "Folder Does not Exist.";
            }
        }
    }
    catch (Exception ex)
    {
        // Exception is displayed on a Label.
        lblErrorMessage.Visible = true;
        lblErrorMessage.Text = ex.Message;
    }
}

/// <summary>
/// This function returns the Folder Path from web.config, 
/// which contains different type of Files. 
/// </summary>
/// <returns>string: Folder Path</returns>
private string GetFolderPath()
{
    // For Example - D:\Projects\SomeProject\SomeFolder
    return (ConfigurationManager.AppSettings != null && 
            ConfigurationManager.AppSettings["FolderPath"] != null) ?
            ConfigurationManager.AppSettings["FolderPath"].ToString() :
            string.Empty;
}

Update

27 Feb 2014 - Added an extra condition in LINQ to check if File Name Ends with .csv only and nothing else.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)
Software Developer Mindfire Solutions
India India
NOW I am a Conference Speaker. Please invite me to your College, Company, Event or Conference !!!

Proud Indian | Microsoft MVP | CodeProject MVP | Author | DZone Most Valuable Blogger | Community Expert | Moderator | jsfiddler | Cricketer | Cook | Dancer

Currently working @Mindfire Solutions.
Love to code and help guys to Trap the Bug.

My Tech Blog

taditdash.wordpress.com

Programming Community Profiles

jsfiddle | Stack Overflow

Other Blog Profiles

Mindfire CRM Team Blog | Mindfire Blog

Social Profiles

Facebook | Twitter | LinkedIn | Google+

Awards

  1. DZone Most Valuable Blogger
  2. Microsoft MVP 2014, 2015
  3. Code Project MVP 2014, 2015
  4. Star Achiever of the Month December 2013
  5. Mindfire Techno Idea Contest 2013 Winner
  6. Star of the Month July 2013

You may also be interested in...

Comments and Discussions

 
GeneralDon't use GetFiles Pin
PaulLinton3-Mar-14 12:01
memberPaulLinton3-Mar-14 12:01 
AnswerRe: Don't use GetFiles Pin
Tadit Dash6-Mar-14 21:03
protectorTadit Dash6-Mar-14 21:03 
QuestionStrange omission Pin
alex2001_ts28-Feb-14 7:26
memberalex2001_ts28-Feb-14 7:26 
AnswerRe: Strange omission Pin
Tadit Dash2-Mar-14 19:12
protectorTadit Dash2-Mar-14 19:12 
GeneralNot only CSV but also CSV* Pin
sditt26-Feb-14 1:09
membersditt26-Feb-14 1:09 
AnswerRe: Not only CSV but also CSV* Pin
Tadit Dash26-Feb-14 20:09
protectorTadit Dash26-Feb-14 20:09 
GeneralRe: Not only CSV but also CSV* Pin
spencepk10-Oct-14 9:45
memberspencepk10-Oct-14 9:45 
GeneralRe: Not only CSV but also CSV* Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)10-Oct-14 17:49
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)10-Oct-14 17:49 
GeneralRe: Not only CSV but also CSV* Pin
spencepk11-Oct-14 3:17
memberspencepk11-Oct-14 3:17 
GeneralRe: Not only CSV but also CSV* Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)11-Oct-14 3:42
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)11-Oct-14 3:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150901.1 | Last Updated 27 Feb 2014
Article Copyright 2014 by Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid