具有所有文件和文件夹的备份目录

时间:2018-07-05 16:05:11

标签: c#

我正在尝试将一个目录复制到另一路径并重命名...

我的位置类似:C:\Backups

我有多个位置,例如(在文本框中):

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

我现在想将包含所有文件和文件夹的所有目录存储到备份路径。

输出文件夹必须类似于->

C:\Backups\05.07.2018_17;00_FullFolderName

我有这个,但这不是理想的...

    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);
    }

1 个答案:

答案 0 :(得分:1)

我自己有这个,希望对您有帮助

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);
   }
}