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(如果文件被更改,这会更改)。