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);
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.
private void PopulateCSVFilesDropDownList()
{
try
{
string folderPath = GetFolderPath();
if (!string.IsNullOrEmpty(folderPath))
{
if (Directory.Exists(folderPath))
{
DirectoryInfo di = new DirectoryInfo(folderPath);
List<string> csvFiles = di.GetFiles("*.csv")
.Where(file => file.Name.EndsWith(".csv") &&
!file.Name.Contains("_something"))
.Select(file => file.Name).ToList();
ddlCSVFiles.DataSource = csvFiles;
ddlCSVFiles.DataBind();
ddlCSVFiles.Items.Insert(0, new ListItem("Please select a file", "-1"));
}
else
{
ddlCSVFiles.Visible = false;
lblErrorMessage.Visible = true;
lblErrorMessage.Text = "Folder Does not Exist.";
}
}
}
catch (Exception ex)
{
lblErrorMessage.Visible = true;
lblErrorMessage.Text = ex.Message;
}
}
private string GetFolderPath()
{
return (ConfigurationManager.AppSettings != null &&
ConfigurationManager.AppSettings["FolderPath"] != null) ?
ConfigurationManager.AppSettings["FolderPath"].ToString() :
string.Empty;
}
Update
- 27th February, 2014 - Added an extra condition in
LINQ
to check if File Name ends with .csv
only and nothing else
CodeProject