Reputation: 1
How can I search an existing file with dynamic file extension and delete it via Regex?
var reg = new Regex(@"\.jpg|\.jpeg|\.png|\.gif|\.bmp");
I can provide file name but I don't know file extension exactly.
Ex: string fileName = "img01";
. I wanna delete these images: img01.jpg
, img01.jpeg
, img01.png
, img01.gif
, img01.bmp
.
Can you give me a sample to do this?
p/s: I don't want to get all files with specific extension in folder and use a loop to delete it.
Upvotes: 2
Views: 1577
Reputation: 6239
You can do this using LINQ and TPL
var reg = new Regex(@"(\.jpg|\.jpeg|\.png|\.gif|\.bmp)$");
Directory.EnumerateFiles(@"C:\temp")
.Where(file => reg.Match(file).Success).AsParallel()
.ForAll(File.Delete)
Or just LINQ
var reg = new Regex(@"(\.jpg|\.jpeg|\.png|\.gif|\.bmp)$");
Directory.EnumerateFiles(@"C:\temp")
.Where(file => reg.Match(file).Success).ToList()
.ForEach(File.Delete)
Upvotes: 7