Reputation:
How can I check if a file has been created in the last x hours? like 23 hours etc. Using C# 3.0.
Note: This must also work if I create the file now, then the file will be seconds old not an hour old yet.
Upvotes: 12
Views: 14960
Reputation: 102478
Something like this...
FileInfo fileInfo = new FileInfo(@"C:\MyFile.txt");
bool myCheck = fileinfo.CreationTime > DateTime.Now.AddHours(-23);
Upvotes: 12
Reputation: 82096
Use:
System.IO.File.GetCreationTime(filename);
To get the creation time of the file, see GetCreationTime for more details and examples.
Then you can do something like:
public bool IsBelowThreshold(string filename, int hours)
{
var threshold = DateTime.Now.AddHours(-hours);
return System.IO.File.GetCreationTime(filename) <= threshold;
}
Upvotes: 12
Reputation: 158309
You can use File.GetCreationTime
and compare to the current 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));
Upvotes: 7
Reputation: 48265
Use FileInfo
class and the CreationTime
property.
FileInfo fi = new FileInfo(@"C:\myfile.txt");
bool check = (DateTime.Now - fi.CreationTime).TotalHours < 23;
Upvotes: 2
Reputation: 96551
FileInfo fi = new FileInfo("c:\\file.txt");
if (fi.CreationTime.AddHours(23) >= DateTime.Now)
{
//created within the last 23 hours
}
Upvotes: 1