How to delete old File

Hi to all,
in the past I have opened a similar post, and tried to adapt it to the specific case, but without success.
I would need some help, in deleting old files, intercepting the date, from the file name.

image

This is the situation.
The goal is to keep only the file from the previous day, or at most 2 days before.
Therefore, the older ones must be deleted.

Can anyone help me with this.
I’m not very good with regular expression and string work.

tnks
aaron

@AaronMark Do you want to delete based on the date that I see on the file name or last modified date

Hi @AaronMark ,

Try the Below Expression :

Directory.GetFiles("YourFolderPath").Where(Function(x)DateTime.ParseExact(Split(x,"_")(0).ToString.Trim,"dd.MM.yyyy",system.Globalization.CultureInfo.InvariantCulture)>=Now.AddDays(-2)).ToArray

The Output of the Above Expression is an Array of String which should be the filenames having dates from previous two days upto Current Date only.

Older than two days:

oldFilesToDelete = (From f In Directory.GetFiles("C:\Temp\old")
Let strDate = System.Text.RegularExpressions.Regex.Match(Path.GetFileName(f), "\d{2}\.\d{2}\.\d{4}").ToString
Where Not String.IsNullOrWhiteSpace(strDate) AndAlso DateTime.ParseExact(strDate, "dd.MM.yyyy",system.Globalization.CultureInfo.InvariantCulture) < Today.AddDays(-2)
Select f
).ToArray

oldFilesToDelete is an array of string. Change -2 to -1 if you want to delete files older than one day.

The result is a list of files (with full path) that you can loop through and delete. Files without a date in their name will be ignored.

image

image

image

1 Like

Top!!

I used your solution.
It was similar to the one I had tried to adapt … but … a little more complex.
I would never have gotten there alone !!
A thousand thanks.
Really a precious help !!

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.