Extended file copy with renaming options
public enum CopyOrRenameMode
{
OnExistsRenameOld,
OnExistsRenameNew,
OnExistsReplace,
OnExistsCancel
}
public static FileInfo FileCopyExt(FileInfo source, DirectoryInfo destDir, CopyOrRenameMode copyMode)
{
var destFile = Path.Combine(destDir.FullName, source.Name);
if (!File.Exists(destFile))
{
File.Copy(source.FullName, destFile, true);
return new FileInfo(destFile);
}
else
{
if (copyMode == CopyOrRenameMode.OnExistsCancel)
return null;
if (copyMode == CopyOrRenameMode.OnExistsReplace)
{
File.Copy(source.FullName, destFile, true);
return new FileInfo(destFile);
}
if (copyMode == CopyOrRenameMode.OnExistsRenameNew)
{
var newDestName = FindNextReplacingFilename(destFile);
File.Copy(source.FullName, newDestName);
return new FileInfo(newDestName);
}
if (copyMode == CopyOrRenameMode.OnExistsRenameOld)
{
var newExistingName = FindNextReplacingFilename(destFile);
File.Move(destFile, newExistingName);
File.Copy(source.FullName, destFile);
return new FileInfo(destFile);
}
}
return null;
}
public static string FindNextReplacingFilename(string filename)
{
int counter = 0;
string proposedDest = filename;
while (counter < 5000)
{
if (File.Exists(proposedDest))
{
counter++;
proposedDest = Path.Combine(Path.GetDirectoryName(filename),
Path.GetFileNameWithoutExtension(filename) +
"_" + counter + Path.GetExtension(filename));
}
else
{
return proposedDest;
}
}
if (counter == 5000)
throw new Exception($"Could not find available file name : too many retries");
return "";
}