-2

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
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
Tamal Banerjee
  • 503
  • 3
  • 20
  • 1
    Possible duplicate of [Fastest way to copy files from one directory to another](https://stackoverflow.com/questions/32236796/fastest-way-to-copy-files-from-one-directory-to-another) – TheGeneral Feb 06 '18 at 02:01

1 Answers1

1

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.

Ctznkane525
  • 7,297
  • 3
  • 16
  • 40