i have write a small code which check on time routine if a zip file is older than 5 hours (300 mint) then the file must be deleted. i have this code. but it is not deleting any file.
string[] zipfiles = Directory.GetFiles("D:\\images\\zipFiles\\", "*.zip*");
foreach (string zip in zipfiles)
{
FileInfo zipinfo = new FileInfo(zip);
string t = zipinfo.CreationTime.ToString();
TimeSpan span = DateTime.Now - zipinfo.CreationTime;
int k =0;
k = span.Minutes;
if (k > 300)
{
zipinfo.Delete();
}
else
{
}
}
You want TimeSpan.TotalMinutes. The Minutes property only returns the minutes portion of the timespan (0-59).
The other answers about using TotalMinutes instead of Minutes are spot on, but since you also asked about the overall logic and code, I thought I might suggest an alternative:
var dir = new DirectoryInfo("D:\\images\\zipFiles\\");
var now = DateTime.Now;
var oldFiles = dir.GetFiles("*.zip")
.Where(f => (now - f.CreationTime).TotalMinutes > 300);
foreach (var file in oldFiles)
file.Delete();
This does the exact same thing as your code, but in a more concise and (in my opinion) readable manner. Because it uses LINQ, you'd need at least .NET 3.5 to compile this code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With