2013-06-02 36 views
0

我使用下面的代碼從一個目錄獲得最新修改的文​​件:如何判斷文件是否在過去一週和過去一個月內被使用?

String tmpPath="C:\demotestDirectory"; 
FileInfo newestFile = GetNewestFile(new DirectoryInfo(tmpPath)); 
if (newestFile != null) 
{ 
    DateTime lastmodifiedDate = newestFile.LastAccessTime; 
    string currentMonth = DateTime.Now.Month.ToString(); 
} 

,我得到的最新修改從目錄提交,現在我想告訴是否該文件已經在過去的一週中使用或不,也是在過去的一個月。

任何幫助表示讚賞。

+0

比較兩個DateTime對象... –

+0

我可以通過獲取當前月份-1來獲取月份部分,並與我的日期進行比較,我在過去的一週中遇到了麻煩。 – confusedMind

+3

關於'LastAccessTime',如果在Windows註冊表中有'NtfsDisableLastAccessUpdate = 1',那麼'LastAccessTime'不會被更新。 – linquize

回答

0

使用此搜尋到7天前:

DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)); 

請注意,你不得到最後一次修改。你上次獲得訪問。最後修改時間使用:LastWriteTime

或者:按您的意見,是這樣的:

DateTime.Now.Subtract(new TimeSpan((int)DateTime.Now.DayOfWeek, 0, 0, 0)); 
+0

我不認爲這聽起來像寫7天不是我正在尋找,它的過去一週和過去一個月!所以我不能使用7天或30天。 – confusedMind

+0

有什麼區別?將上次修改將不會像上次訪問一樣? – confusedMind

+0

@confusedMind爲什麼這與月份不同 - 你在評論中寫到你減去30天? – ispiro

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."); 
     } 
    } 

} 

這段代碼首先檢查文件是在同一年進行編輯。它檢查它的月份。然後它使用帶有當前日期時間信息的日曆類(其中包含以下內容:一週內有多少天,這是一週中的第一天等)。函數GetWeekOfYear返回星期數。這兩個整數進行比較,然後你走!

注:

您使用的LastAccessTime,但這也更新,當您在文件上做的小東西像雙擊它,在資源管理器(所以不是很有益的,如果你想知道,如果用戶真的開它)。改爲使用LastWriteTime(如果文件已更改,則更改)。

0

,你可以這樣做:

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); 
} 

由於文件已經在上週被使用,這也意味着它已經在上個月使用。

相關問題