在C#.NET中,如何将文件复制到另一个位置,如果源文件比现有文件更新(稍后有“修改日期”),则覆盖现有文件,并注意源文件是否较旧?
答案 0 :(得分:31)
您可以使用FileInfo
class及其属性和方法:
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);
}
}
答案 1 :(得分:8)
您可以使用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) ;
}
答案 2 :(得分:1)
以下是我对答案的看法:复制不会移动文件夹内容。如果目标不存在,则代码更清晰易读。从技术上讲,为不存在的文件创建一个fileinfo,其LastWriteTime为DateTime.Min,因此将复制,但在可读性方面略有不足。我希望这个经过测试的代码有助
**编辑:我已将我的源代码更新为更灵活。因为它是基于这个线程我在这里发布了更新。使用掩码时,如果子文件夹不包含匹配的文件,则不会创建。在你的未来,肯定会有一个更强大的错误处理程序。 :)
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);
}
}
答案 3 :(得分:0)
在批处理文件中,这将起作用:
XCopy "c:\my directory\source.ext" "c:\my other directory\dest.ext" /d