文件夹中有许多文件。每当任何文件中有任何更新时,我都会在我的windows服务应用程序中收到一个事件。
我正在寻找一些东西,通过它我可以验证具有特定模式的文件。如果匹配,则只应处理该文件,否则应忽略该文件。
像这样的
if(File.Matches("genprice*.xml"))
{
DoSomething();
}
- genprice20212604.xml
- genprice20212704.xml
- 价格20212604.xml
- genprice20212704.txt
从上面来看,只有#1和#2应该被处理,其他应该被忽略。
您可以尝试使用正则表达式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace ConsoleAppRegex
{
class Program
{
static void Main(string[] args)
{
string[] fileNames = new string[] { "genprice20212604.xml",
"genprice20212704.xml",
"price20212604.xml",
"genprice20212704.txt"};
Regex re = new Regex(@"genprice[^.]*.xml");
foreach (string fileName in fileNames)
{
if (re.Match(fileName).Success)
{
Console.WriteLine(fileName);
}
}
Console.ReadLine();
}
}
}
我建议使用Regex:
using System.Text.RegularExpressions;
using System.IO;
var reg = new Regex(@"genpriced{8}$");
var fileNamesFromFolder = Direcotory.GetFiles(" @Folder´s path ", "*.xml")
.Where(path => reg.IsMatch(Path.GetFileNameWithoutExtension(path)))
.Select(Folder=>
Path.GetFileNameWithoutExtension(Folder));
foreach (var file in fileNamesFromFolder )
{
//Do something...
}