2014-09-02 61 views
1

我在我的SSIS包中編寫了一個腳本任務,以便刪除包中使用的日誌文件,如果它早於X天數。這裏是我當前的代碼:刪除然後重新創建x天以前的文件c#保留createdDate

if (File.Exists((String)Dts.Variables["ErrorLogLocation"].Value)) 
     { 

      DateTime logCreatedDate = File.GetCreationTime((String)Dts.Variables["ErrorLogLocation"].Value); 

      if (logCreatedDate < DateTime.Now.AddDays(-3)) 
      { 
       try 
       { 
        File.Delete((String)Dts.Variables["ErrorLogLocation"].Value); 
       } 
       catch (Exception e) 
       { 
        using (StreamWriter sw = File.AppendText((String)Dts.Variables["ErrorLogLocation"].Value)) 
        { 
         sw.WriteLine(DateTime.Now + " : "+ e); 
        } 
       } 

       using (StreamWriter sw = File.AppendText((String)Dts.Variables["ErrorLogLocation"].Value)) 
       { 
        sw.WriteLine("New log Creation Date: " + File.GetCreationTime((String)Dts.Variables["ErrorLogLocation"].Value)); 
       } 

      } 
     } 

好像它的工作,但問題是,當我刪除的文件,然後寫入到具有相同名稱的新文件,將內部信息被預期擦拭,但文件創建日期與刪除之前保持一致。這是一個問題,因爲我基於何時在該日期時間刪除此文件。在我看來,預期的行爲是刪除文件,然後用新的創建日期寫入一個全新的文件。

任何想法可能會導致此?這是由於我刪除一個文件,然後立即附加到一個具有相同名稱的文件(我假設它會創建一個新文件,如果它不存在?),這個文件仍然保存在內存中期?

回答

1

documentation

NTFS格式的驅動器可以高速緩存有關文件的信息,如文件 創建時間,對很短的時間週期。因此,如果您是 覆蓋或替換現有文件,則可能需要 以顯式設置文件的創建時間。

基於此信息,您必須致電File.SetCreationTime以確保它獲得所需的時間戳。

+0

我想它是緩存的東西。謝謝! – Dingus 2014-09-02 17:03:20