c#中如何基于文件名格式过滤文件
本文关键字:格式 过滤 文件 文件名 何基于 | 更新日期: 2023-09-27 18:17:16
我需要从FTP服务器下载具有特定文件名格式的文件。服务器中的文件名可能如下所示:
- o - 0098 - 00009801 - _08052014054258.xml
- 订单编号3359_08062014121815.xml
- o - 0302 - 00022043 - _07312014085513.xml
- O-LABELS_94920235569876.XML
- 乔ANN_08062014170911.xml
- o - 0233 - 00026378 - _07312014155245.xml
- LABELS_08052014174907.xml
我只想下载文件名格式为o - xxxx - xxxxxxxx_xxxxxxxxxxxx .xml的文件
我使用下面的代码,但它不是很有效。什么是最有效的方法,只选择与上述文件名格式的文件?
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
while (!reader.EndOfStream)
{
fileName = reader.ReadLine();
if (fileName.ToUpper().IndexOf("O-") > -1)
files.Add(fileName);
}
}
}
结果是只选择这些文件:
- o - 0098 - 00009801 - _08052014054258.xml
- o - 0233 - 00026378 - _07312014155245.xml
- o - 0302 - 00022043 - _07312014085513.xml
假设您已经将文件列表存储在List<string>
中,则提取非常简单
List<string> files = new List<string>()
{
"O-0098-00009801_08052014054258.xml",
"ORDER ID 3359_08062014121815.xml",
"O-0302-00022043_07312014085513.xml",
"O-LABELS_94920235569876.XML",
"JO ANN_08062014170911.xml",
"O-0233-00026378_07312014155245.xml",
"LABELS_08052014174907.xml"
};
Regex r = new Regex(@"O-'d{4}-'d{8}_'d{14}");
var result = files.Where(x => r.IsMatch(x)).ToList();
你可以这样做:
List<string> orders = new List<string>()
{
"O-0098-00009801_08052014054258.xml",
"ORDER ID 3359_08062014121815.xml",
"O-0302-00022043_07312014085513.xml",
"O-LABELS_94920235569876.XML",
"JO ANN_08062014170911.xml",
"O-0233-00026378_07312014155245.xml",
"LABELS_08052014174907.xml"
};
List<string> valid = new List<string>()
{
"O-0098-00009801_08052014054258.xml",
"O-0302-00022043_07312014085513.xml",
"O-0233-00026378_07312014155245.xml"
};
List<string> order = orders.Where(x => valid.Contains(x)).ToList();
如果您有有效/总List
,您可以按照上述方式进行操作。否则你可以使用正则表达式,如Steve answer .