Name a backup but that does not match the previous C #

2

My code makes a backup of a folder, if the backup folder exists it creates another by adding "_1" and if it does not exist it creates a new one. I do not know how to do it so that when there is more than one backup folder it automatically generates another without matching the name, I leave here the code that I have achieved 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);
        }
    }
}
    
asked by LopezAi 06.10.2017 в 09:42
source

1 answer

2

There are many solutions to your problem. You can, as you are told 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:

while (Directory.Exists(destDirName)) //repetimos hasta que no exista el directorio
{
    int indice = 0;
    var splitted = destDirName.Split('_'); //separamos el nombre para obtener el número secuencial

    if (int.TryParse(splitted.Last(), out indice))
    {
        //si la última parte del nombre es un numero, lo incrementamos
        indice++;
    }

    if (splitted.Length > 1)
    {
        //unimos el nombre de la carpera quitando la última parte (_X) 
        //y le añadimos el nuevo indice
        destDirName = String.Join("", splitted.Reverse().Skip(1).Reverse()) + "_" + indice.ToString(); 
    }
    else
    {
        //si no era un número, añadimos _1
        destDirName+= "_" + indice.ToString();
    }
}

//una vez tenemos un nombre único, creamos la carpeta
Directory.CreateDirectory(destDirName);
    
answered by 06.10.2017 / 10:21
source