Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timespan problem

Tags:

c#

timespan

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
    { 

    }
}
like image 622
safi Avatar asked Feb 16 '26 11:02

safi


2 Answers

You want TimeSpan.TotalMinutes. The Minutes property only returns the minutes portion of the timespan (0-59).

like image 162
Talljoe Avatar answered Feb 19 '26 00:02

Talljoe


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.

like image 22
Joel Mueller Avatar answered Feb 18 '26 23:02

Joel Mueller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!