It appears that what you need is an algorithm to copy files with file names appropriately incremented. This will do what you're looking for.
Say these are you file and archive directory names.
var file = @"Data/A.txt";
var archive = @"Data/Archive";
We see if the last write time condition is satisfied. If so, we enumerate all files in your destination directory that match your original file patter. That is, it must start with A
, then it may or may not have (1)
etc. So all files such as A.txt
, A(1).txt
, A(2).txt
are enumerated. Then we get the last of those files in order (and here we must be careful to sort by length, if you simply sort by value, A.txt
will come after all others). Then using a Regex
we get the last file's number, increment, and copy file with the new name.
if (File.GetLastWriteTime(file) > DateTime.Today)
{
var fileNameOnly = Path.GetFileNameWithoutExtension(file);
var ext = Path.GetExtension(file);
var pattern = fileNameOnly + "*" + ext;
var lastCopy = Directory.EnumerateFiles(archive, pattern, System.IO.SearchOption.TopDirectoryOnly)
.OrderBy(x => x.Length)
.LastOrDefault();
var newName = fileNameOnly + ext;
if (lastCopy != null)
{
var lastCopyNameOnly = Path.GetFileNameWithoutExtension(lastCopy);
var match = Regex.Match(lastCopyNameOnly, @"(.+)\((\d+)\)");
int lastNum = 1;
if (match.Success)
{
int.TryParse(match.Groups[2].Value, out lastNum);
lastNum++;
}
newName = string.Format("{0}({1}){2}", fileNameOnly, lastNum, ext);
}
var dest = Path.Combine(archive, newName);
File.Copy(file, dest);
}
Note
Be careful about var lastNum = 1;
initializatin as well. You must initialize to 1
, not zero
. Because if the match.Success == false
, that mean you have only the A.txt
file in the destination, so then your next file will be A(1).txt
. If you initialized it to zero
, then your next file will be A(0).txt
which isn't what your desired output is.