简体   繁体   中英

Fastest way to create and move backup files to a directory?

I want to create a backup file before performing any operation on the file and then move it a to a location with the folder structure being D:\\BACKUP\\(Date)\\(Time) .

What is the fastest way of doing it? I'm currently doing it as below

string path = textBox1.Text;
var files = Directory.GetDirectories(path, "dtpo", SearchOption.AllDirectories)
                     .SelectMany(t => Directory.GetFiles(t, "*.txt")).ToArray();

foreach (var file in files)
{
    File.Copy(file,file+".bk",true);
    string OnlyDate=DateTime.Today.ToString("dd-MM-yyyy");
    string OnlyTime = DateTime.Now.ToString("hh-mm-ss");
    if (!Directory.Exists(@"D:\BACKUP\" + OnlyDate+"\\"+OnlyTime))
    {
        Directory.CreateDirectory(@"D:\BACKUP\" + OnlyDate+"\\"+OnlyTime);
    }

    string rootFolderPath = Path.GetFullPath(file+".bk");
    string targetPath=@"D:\BACKUP\" + OnlyDate+"\\"+OnlyTime+"\\"+Path.GetFileName(file+".bk");
    File.Move(rootFolderPath, targetPath);
    //Do the processes
}

Directory.exists can be bypassed, createdirectory won't run if it does. Also recommend you don't do 2 io operations to write the file. Just write directly to the output using file.copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM