我想做一些事情
答案 0 :(得分:0)
如果目标不存在,则使用“||!destFile.Exists”更清楚地读取代码。从技术上讲,为不存在的文件创建一个fileinfo,其LastWriteTime为DateTime.Min,因此将复制,但在可读性方面略有不足。更健壮的错误处理程序将是理想的,但这是另一个主题。 :)我希望这个经过测试的代码有助于某人
复制xcopy源目标/ d
等文件CopyFolderContents(sourceFolder, destinationFolder);
复制xcopy源目标/ d / s等文件
CopyFolderContents(sourceFolder, destinationFolder, "*.*", true, true);
使用可选的掩码
复制上述任何文件CopyFolderContents(sourceFolder, destinationFolder, "*.png", true, true);
将所有文件从源文件夹和子文件夹复制到目标文件夹
CopyFolderContents(sourceFolder, destinationFolder, "*.*", false, true);
这里包含的问题是带有重载的代码,以方便您使用。
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);
}
}