My code makes a backup of a folder, if the backup folder exists it creates another adding "_1" and if it doesn't it creates a new one. I don't know how to make it so that when there is more than one backup folder, it automatically generates another one without the name matching, I leave you here the code that I have obtained so far:
//backup del directorio destino en otra carpeta
private static void directoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
if (Directory.Exists(destDirName))
{
destDirName = destDirName + "_1";
Directory.CreateDirectory(destDirName);
}
else
// If the destination directory doesn't exist, create it.
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
directoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
There are many solutions to your problem. You can, as they tell you in another answer, use the date and time. You can use a guid so that the folder is always unique.
I give you a solution so that the folders always end in a sequential number (_1,_2,_3...). It is not very optimized, but it can help you see how to do it: