检查是否在最近X小时内创建了文件

12 c#

如何检查最近x小时内是否创建了文件?像23小时等.使用C#3.0.

注意:如果我现在创建文件,这也必须工作,那么文件将是几秒钟而不是一个小时.

Rob*_*Day 12

像这样......

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

  • 您将最后两行合并为<pre> bool myCheck = fileinfo.CreationTime> DateTime.Now.AddHours(-23); </ PRE> (2认同)

Jam*_*mes 11

使用:

System.IO.File.GetCreationTime(filename);
Run Code Online (Sandbox Code Playgroud)

要获取文件的创建时间,请参阅GetCreationTime以获取更多详细信息和示例.

然后你可以这样做:

public bool IsBelowThreshold(string filename, int hours)
{
     var threshold = DateTime.Now.AddHours(-hours);
     return System.IO.File.GetCreationTime(filename) <= threshold;
}
Run Code Online (Sandbox Code Playgroud)


Fre*_*örk 6

您可以使用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));
Run Code Online (Sandbox Code Playgroud)