[ACCEPTED]-Check If File Created Within Last X Hours-c#

Accepted answer
Score: 12

Something like this...

        FileInfo fileInfo = new FileInfo(@"C:\MyFile.txt"));
        bool myCheck = fileinfo.CreationTime > DateTime.Now.AddHours(-23); 

0

Score: 12

Use:

System.IO.File.GetCreationTime(filename);

To get the creation time of the file, see 2 GetCreationTime for more details and examples.

Then you 1 can do something like:

public bool IsBelowThreshold(string filename, int hours)
{
     var threshold = DateTime.Now.AddHours(-hours);
     return System.IO.File.GetCreationTime(filename) <= threshold;
}
Score: 7

You can use File.GetCreationTime and compare to the current 1 time:

private static bool IsFileOlder(string fileName, TimeSpan thresholdAge)
{
    return (DateTime.Now - File.GetCreationTime(fileName)) > thresholdAge;
}

// used like so:
// check if file is older than 23 hours
bool oldEnough = IsFileOlder(@"C:\path\file.ext", new TimeSpan(0, 23, 0, 0));
// check if file is older than 23 milliseconds
bool oldEnough = IsFileOlder(@"C:\path\file.ext", new TimeSpan(0, 0, 0, 0, 23));
Score: 2

Use FileInfo class and the CreationTime property.

FileInfo fi = new FileInfo(@"C:\myfile.txt");
bool check = (DateTime.Now - fi.CreationTime).TotalHours < 23;

0

Score: 1
    FileInfo fi = new FileInfo("c:\\file.txt");
    if (fi.CreationTime.AddHours(23) >= DateTime.Now)
    {
        //created within the last 23 hours
    }

0

More Related questions