2011-08-23 51 views

Trả lời

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

Bạn sẽ không phải gọi 'Làm mới' trên 'đích' (hoặc tạo sau) để nhận giá trị chính xác khi tệp đích đã tồn tại? –

+0

@Paul Ruane: Bạn nói đúng - Tôi đã cập nhật câu trả lời cho phù hợp, cảm ơn bạn. –

2

Bạn sẽ có thể đọc các giá trị bạn cần, thực hiện bất kỳ thay đổi nào bạn muốn và sau đó khôi phục các giá trị trước đó bằng cách sử dụng các thuộc tính của FileInfo.

11

Khi thực hiện mà không cần quyền quản trị câu trả lời của Roy sẽ ném một ngoại lệ (UnauthorizedAccessException) khi cố gắng ghi đè lên hiện chỉ đọc các tập tin hoặc khi cố gắng thiết lập các timestamps trên sao chép đọc các tập tin duy nhất.

Giải pháp sau đây dựa trên câu trả lời của Roy nhưng mở rộng nó để ghi đè lên tệp chỉ đọc và thay đổi dấu thời gian trên tệp chỉ đọc được sao chép trong khi vẫn giữ thuộc tính chỉ đọc của tệp trong khi vẫn thực thi mà không có đặc quyền quản trị.

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; 
    } 
} 
Các vấn đề liên quan