[英]Copy file, overwrite if newer
在C#.NET中,如何將文件復制到另一個位置,如果源文件比現有文件更新(稍后有“修改日期”),則覆蓋現有文件,並注意源文件是否較舊?
您可以使用FileInfo
類及其屬性和方法:
FileInfo file = new FileInfo(path);
string destDir = @"C:\SomeDirectory";
FileInfo destFile = new FileInfo(Path.Combine(destDir, file.Name));
if (destFile.Exists)
{
if (file.LastWriteTime > destFile.LastWriteTime)
{
// now you can safely overwrite it
file.CopyTo(destFile.FullName, true);
}
}
您可以使用FileInfo類:
FileInfo infoOld = new FileInfo("C:\\old.txt");
FileInfo infoNew = new FileInfo("C:\\new.txt");
if (infoNew.LastWriteTime > infoOld.LastWriteTime)
{
File.Copy(source path,destination path, true) ;
}
以下是我對答案的看法:復制不會移動文件夾內容。 如果目標不存在,則代碼更清晰易讀。 從技術上講,為不存在的文件創建一個fileinfo將具有DateTime.Min的LastWriteTime,因此它會復制但在可讀性方面略有不足。 我希望這個經過測試的代碼有助
**編輯:我已經更新了我的源代碼,以便更靈活。 因為它是基於這個線程我在這里發布了更新。 使用掩碼如果子文件夾不包含匹配的文件,則不會創建子目錄。 在你的未來,肯定會有一個更強大的錯誤處理程序。 :)
public void CopyFolderContents(string sourceFolder, string destinationFolder)
{
CopyFolderContents(sourceFolder, destinationFolder, "*.*", false, false);
}
public void CopyFolderContents(string sourceFolder, string destinationFolder, string mask)
{
CopyFolderContents(sourceFolder, destinationFolder, mask, false, false);
}
public void CopyFolderContents(string sourceFolder, string destinationFolder, string mask, Boolean createFolders, Boolean recurseFolders)
{
try
{
if (!sourceFolder.EndsWith(@"\")){ sourceFolder += @"\"; }
if (!destinationFolder.EndsWith(@"\")){ destinationFolder += @"\"; }
var exDir = sourceFolder;
var dir = new DirectoryInfo(exDir);
SearchOption so = (recurseFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
foreach (string sourceFile in Directory.GetFiles(dir.ToString(), mask, so))
{
FileInfo srcFile = new FileInfo(sourceFile);
string srcFileName = srcFile.Name;
// Create a destination that matches the source structure
FileInfo destFile = new FileInfo(destinationFolder + srcFile.FullName.Replace(sourceFolder, ""));
if (!Directory.Exists(destFile.DirectoryName ) && createFolders)
{
Directory.CreateDirectory(destFile.DirectoryName);
}
if (srcFile.LastWriteTime > destFile.LastWriteTime || !destFile.Exists)
{
File.Copy(srcFile.FullName, destFile.FullName, true);
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace);
}
}
在批處理文件中,這將起作用:
XCopy "c:\my directory\source.ext" "c:\my other directory\dest.ext" /d
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.