2011-08-23 88 views

回答

15
public static void CopyFileExactly(string copyFromPath, string copyToPath) 
{ 
    var origin = new FileInfo(copyFromPath); 

    origin.CopyTo(copyToPath, true); 

    var destination = new FileInfo(copyToPath); 
    destination.CreationTime = origin.CreationTime; 
    destination.LastWriteTime = origin.LastWriteTime; 
    destination.LastAccessTime = origin.LastAccessTime; 
} 
+1

當目標文件已經存在時,您不需要在'destination'(或稍後創建)調用'Refresh'來獲取正確的值嗎? –

+0

@ Paul Ruane:你說得對 - 我已經更新了相應的答案,謝謝。 –

2

你應該能夠閱讀您需要的值,做出您希望的任何更改,然後恢復以前的值通過使用FileInfo的屬性。

11

當執行沒有管理權限羅伊的回答試圖覆蓋現有隻讀文件或試圖設置複製只讀文件的時間戳時,當會拋出異常(UnauthorizedAccessException)。

以下解決方案基於Roy的回答,但將其擴展爲覆蓋只讀文件,並更改複製的只讀文件的時間戳,同時保持文件的只讀屬性,同時仍在執行而無需管理員權限。

public static void CopyFileExactly(string copyFromPath, string copyToPath) 
{ 
    if (File.Exists(copyToPath)) 
    { 
     var target = new FileInfo(copyToPath); 
     if (target.IsReadOnly) 
      target.IsReadOnly = false; 
    } 

    var origin = new FileInfo(copyFromPath); 
    origin.CopyTo(copyToPath, true); 

    var destination = new FileInfo(copyToPath); 
    if (destination.IsReadOnly) 
    { 
     destination.IsReadOnly = false; 
     destination.CreationTime = origin.CreationTime; 
     destination.LastWriteTime = origin.LastWriteTime; 
     destination.LastAccessTime = origin.LastAccessTime; 
     destination.IsReadOnly = true; 
    } 
    else 
    { 
     destination.CreationTime = origin.CreationTime; 
     destination.LastWriteTime = origin.LastWriteTime; 
     destination.LastAccessTime = origin.LastAccessTime; 
    } 
}