2016-12-02 129 views
-1

我試圖獲取目錄中文件的最後修改時間。我遍歷目錄並打印修改日期。輸出結果顯示出10個文件(在其他文件夾上也有不同數量的文件)。在命令提示符中出現10個文件。所有這些打印12/31/1600。當文件存在時GetLastWriteTime不準確

我該如何修復它才能打印正確的日期?

Dim strFilepath = "C:\Test" 'Test folder contains 10 files for test 
Dim File As System.IO.FileInfo() = directory.GetFiles() 
Dim File1 As System.IO.FileInfo 
Dim strLastModified As String 

For Each File1 In File 'Loops the GetLastWriteTime 
    strLastModified = System.IO.File.GetLastWriteTime(strFilepath & File.ToString()).ToShortDateString() 
    Console.WriteLine(strLastModified)'Prints all 10 files but with the 12/31/1600 date 
    'Files do exist, code goes into file, it loops through it but wrong date. 
+0

[獲取上次寫入時間可能重複返回一個奇怪的值](http://stackoverflow.com/questions/20306688/get-last-write-time-is-returning-a-strange-value) –

回答

1

吉姆給了你已經的原因,爲什麼你的日期與他的鏈接到dup。

您Concat的strFilepathFile.ToString()錯誤,因爲你缺少它們之間的反斜槓\,從而讓類似:
C:\TestYourFile.txt

另外,您在For Each中使用了錯誤的變量。 它應該是File1而不是File(謝謝@馬克)。

解決方案1:
That's爲什麼是Path.Combine功能的原因。

所以更改

strLastModified = System.IO.File.GetLastWriteTime(strFilepath & File.ToString()).ToShortDateString() 

strLastModified = System.IO.File.GetLastWriteTime(Path.Combine(strFilepath, File1.ToString())).ToShortDateString() 

解決方案2:
像馬克評論說,你可以只使用FullName屬性,這使得它更容易:

strLastModified = System.IO.File.GetLastWriteTime(File1.FullName).ToShortDateString() 
+0

它應該也是'File1',因爲'File'是'FileInfo'的數組(但'ToString()'可能已經給出了完整的路徑)。也許使用'File1.FullPath'來代替,所以你不需要組合任何東西? – Mark

+0

偉大的通知@馬克我會將它納入我的答案。謝謝! –