C# 检查文件是否在过去 X 小时内创建
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1119158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check If File Created Within Last X Hours
提问by
How can I check if a file has been created in the last x hours? like 23 hours etc. Using C# 3.0.
如何检查在过去 x 小时内是否创建了文件?像 23 小时等。使用 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.
注意:如果我现在创建文件,这也必须有效,那么文件将是几秒钟而不是一小时。
采纳答案by James
Use:
用:
System.IO.File.GetCreationTime(filename);
To get the creation time of the file, see GetCreationTimefor more details and examples.
要获取文件的创建时间,请参阅GetCreationTime以获取更多详细信息和示例。
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;
}
回答by Robin Day
Something like this...
像这样的东西...
FileInfo fileInfo = new FileInfo(@"C:\MyFile.txt"));
bool myCheck = fileinfo.CreationTime > DateTime.Now.AddHours(-23);
回答by bruno conde
Use FileInfo
class and the CreationTime
property.
使用FileInfo
类和CreationTime
属性。
FileInfo fi = new FileInfo(@"C:\myfile.txt");
bool check = (DateTime.Now - fi.CreationTime).TotalHours < 23;
回答by Fredrik M?rk
You can use File.GetCreationTime
and compare to the current time:
您可以使用File.GetCreationTime
并与当前时间进行比较:
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));
回答by M4N
FileInfo fi = new FileInfo("c:\file.txt");
if (fi.CreationTime.AddHours(23) >= DateTime.Now)
{
//created within the last 23 hours
}