-1

I'm trying to copy one directory to another path and rename it...

I have a location like: C:\Backups

I have multiple locations such as (in a textbox):

C:\Users\xy\AppData\Local\....
C:\ProgramData\Test
C:\Tests\Test

I want now store all directory with all Files and Folders to the Backup Path..

Output Folder must looks like ->

C:\Backups\05.07.2018_17;00_FullFolderName

I Have this, but this isnt ideal...

    this.CopyAll(new DirectoryInfo(@"C:\Test"), new DirectoryInfo(@"C:\Backups"));


    private void CopyAll(DirectoryInfo oOriginal, DirectoryInfo oFinal)
    {
        foreach (DirectoryInfo oFolder in oOriginal.GetDirectories())
            this.CopyAll(oFolder, oFinal.CreateSubdirectory(oFolder.Name));

        foreach (FileInfo oFile in oOriginal.GetFiles())
            oFile.CopyTo(oFinal.FullName + @"\" + oFile.Name, true);
    }
Deparli
  • 33
  • 7
  • 3
    What do you mean it "isn't ideal"? –  Jul 05 '18 at 16:11
  • Probably you can use this approach? https://stackoverflow.com/questions/58744/how-to-copy-the-entire-contents-of-directory-in-c – mezinman Jul 05 '18 at 16:14
  • Making backups to the same drive is indeed not ideal. Lose the drive, lose the backups as well. Do consider leaving it up to the OS to do it for you: https://www.howtogeek.com/74623/how-to-use-the-new-file-history-feature-in-windows-8/ – Hans Passant Jul 05 '18 at 16:23
  • @CetinBasoz it looks like it does. "isn't ideal" can mean a lot of things, among them being "its too slow" or "i dont like the way this code looks". I don't think you can answer for the OP. –  Jul 05 '18 at 16:47
  • @CetinBasoz is it obvious that it isn't copying files in subfolders? Because it is, recursively, by calling `CopyAll`. –  Jul 05 '18 at 16:54

1 Answers1

1

I had this for myself, hope helps:

void Main()
{
    string baseFolder = @"c:\Backups";
    string source = @"C:\Tests\Test";
    string target = Path.Combine(baseFolder, DateTime.Now.ToString("yyyyMMddHHmmss"));
    if (!Directory.Exists(baseFolder))
    {
        Directory.CreateDirectory( baseFolder );
    }
    CopyFolder( source, target );
}


private void CopyFolder(string source, string destinationBase)
{
    CopyFolder( new DirectoryInfo( source ), destinationBase );
    foreach (DirectoryInfo di in new DirectoryInfo(source).GetDirectories("*.*", SearchOption.AllDirectories))
    {
      CopyFolder( di, destinationBase );
    }
}

private void CopyFolder( DirectoryInfo di, string destinationBase )
{
   string destinationFolderName = Path.Combine( destinationBase, di.FullName.Replace(":",""));
   if ( !Directory.Exists( destinationFolderName ) )
   {
      Directory.CreateDirectory( destinationFolderName );
   }
   foreach (FileInfo fi in di.GetFiles())
   {
      fi.CopyTo( Path.Combine(destinationFolderName, fi.Name), false);
   }
}
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39