使用 LINQ 获取特定文件类型的文件名






4.87/5 (7投票s)
这是一个简单的技巧,用于查找文件夹中特定文件类型的文件名。
这是一个简单的技巧,用于查找文件夹中特定**文件类型**的**文件名**。
背景
假设你想查找文件夹中的**CSV 文件**的**文件名**。因此,你需要排除所有其他文件,只考虑**CSV 文件**。这在我的一个项目中被实现,所有来自一个文件夹的**CSV 文件名**都被填充到一个 DropDownList
中。
让我们探索一下
所以,这里的主要事情是找到特定类型的 文件
。为此,我使用了以下代码
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();
在这里,我使用了 DirectoryInfo.GetFiles 方法 (String)。
返回与给定搜索模式匹配的当前目录中的文件列表。
因此,di.GetFiles(“*.csv”)
将会给我们一个包含该文件夹中所有**CSV 文件**的列表。
- 这里 *.csv 是
SearchPattern
,而*
表示 .csv 之前的任何字符串
。 - 现在,使用
Where
子句来确保**文件扩展名**以 .csv 结尾,且没有其他内容。
然后,我们通过 Select
子句选择**文件名**,例如 Select(file => file.Name)
。
注意
你可以将此技巧应用于查找任何**文件类型**。你只需要相应地更改 SearchPattern
。如果你想查找 pdf
文件,那么它将是 di.GetFiles("*.pdf")
。
完整代码
我在这里使用了另一个 Where
条件,根据要求排除文件名中包含 _something
的**CSV 文件**。
/// <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;
}
更新
- 2014 年 2 月 27 日 - 在
LINQ
中添加了一个额外的条件,以检查文件名是否仅以.csv
结尾,且没有其他内容