我使用以下代码从目录中获取最新修改的文件:
String tmpPath="C:demotestDirectory";
FileInfo newestFile = GetNewestFile(new DirectoryInfo(tmpPath));
if (newestFile != null)
{
DateTime lastmodifiedDate = newestFile.LastAccessTime;
string currentMonth = DateTime.Now.Month.ToString();
}
我从目录中得到了最新修改的文件,现在我想知道这个文件在过去的一周和过去的一个月里是否被使用过。
感谢您的帮助。
使用此查找7天前:
DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0));
请注意,上次修改的不是。您最近一次访问。上次修改时间使用:LastWriteTime。
或者:根据你的评论,类似于:
DateTime.Now.Subtract(new TimeSpan((int)DateTime.Now.DayOfWeek, 0, 0, 0));
FileInfo fi = new FileInfo(/*filename*/);
DateTime dateFile = fi.LastWriteTime;
DateTime now = DateTime.Now;
if (now.Year == dateFile.Year) { //same year?
if (now.Month == dateFile.Month) { //same month?
MessageBox.Show("File has been edited in this month.");
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar c = dfi.Calendar;
int fileWeek = c.GetWeekOfYear(dateFile, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
int nowWeek = c.GetWeekOfYear(now, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
if (fileWeek == nowWeek) { //same week?
MessageBox.Show("File has been edited in this week.");
}
}
}
此代码首先检查文件是否在同一年进行了编辑。它检查它的月份。然后,它使用具有当前DateTimeInfo的日历类(其中包括:一周中有多少天,这是一周的第一天,等等(。函数GetWeekOfYear返回周数。这两个整数比较一下,你就走!
注:
你使用了LastAccessTime,但当你在文件上做一些小事情时,比如在资源管理器中点击它时,它也会更新(所以如果你想知道用户是否真的打开了它,这不是很有帮助(。请改用LastWriteTime(如果文件已更改,则此选项会更改(。
您可以这样做:
private void fileUsage()
{
String tmpPath = "C:\demotestDirectory";
FileInfo newestFile = GetNewestFile(new DirectoryInfo(tmpPath));
if (newestFile != null)
{
DateTime currunt = DateTime.Now;
DateTime old = newestFile.LastAccessTime;
System.TimeSpan t = currunt.Subtract(old);
double lastmodifiedDate = t.TotalMilliseconds;
if (lastmodifiedDate <= 604800000)
{
Console.WriteLine("The File " + newestFile.Name + " has been used at " + newestFile.LastAccessTime.ToLocalTime());
}
}
}
private FileInfo GetNewestFile(DirectoryInfo directoryInfo)
{
var myFile = (from f in directoryInfo.GetFiles()
orderby f.LastWriteTime descending
select f).First();
return new FileInfo(myFile.FullName);
}
由于该文件已在上周使用,这也意味着它已在上个月使用。