I want to do a few things
- copy files like xcopy source target /d
- copy files like xcopy source target /d /s
- copy any above files using an optional mask
- copy all files from source and sub-folders to the target folder
I want to do a few things
If the target does not exist the code is clearer to read using "|| !destFile.Exists". Technically, creating a fileinfo for a non existent file will have a LastWriteTime of DateTime.Min so it would copy but falls a little short on readability. A more robust error handler would be ideal but that's another topic. :) I hope this tested code helps someone.
copy files like xcopy source target /d
CopyFolderContents(sourceFolder, destinationFolder);
copy files like xcopy source target /d /s
CopyFolderContents(sourceFolder, destinationFolder, "*.*", true, true);
copy any above files using an optional mask
CopyFolderContents(sourceFolder, destinationFolder, "*.png", true, true);
copy all files from source and sub-folders to the target folder
CopyFolderContents(sourceFolder, destinationFolder, "*.*", false, true);
that wraps up the questions here is the code with overloads for your convenience.
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);
}
}
© 2022 - 2024 — McMap. All rights reserved.