예제 #1
0
        private bool Backup(out Exception exception)
        {
            Stopwatch sw = new Stopwatch();

            //The name of the backup zip file. Not the full path only the file name
            string zipName = $"{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day}_{DateTime.Now.Hour}-{DateTime.Now.Minute}-{DateTime.Now.Second}.zip";

            //Begins Backup
            try
            {
                sw.Start();
                using (FileStream fs = File.Create(Path.Combine(settings.BackupLocation, zipName)))
                {
                    fs.CompressZip(settings.BackupSource, settings.ZipCompressionLevel, true);
                }
                sw.Stop();
                ConsoleWriter.WriteLine("Created backup in " + sw.ElapsedMilliseconds + " ms", consoleColor);
            }
            catch (Exception ex)
            {
                sw.Stop();
                if (File.Exists(Path.Combine(settings.BackupLocation, zipName)))
                {
                    File.Delete(Path.Combine(settings.BackupLocation, zipName));
                }
                exception = ex;
                return false;
            }

            //Enqueues the new backup into settings for saving
            backups.Enqueue(Path.Combine(settings.BackupLocation, zipName));

            //Removes excess backups
            CleanUp();

            //save new backuplist queue to BackupList.json
            try
            {
                string json = JsonConvert.SerializeObject(backups.ToArray(), Formatting.Indented);
                File.WriteAllText(@"Wrapper\BackupList.json", json);
            }
            catch (Exception ex)
            {
                ExceptionPrinter.PrintException(ex, "Error writing backups to BackupList.json");
            }

            //cleanUp.Wait();
            exception = null;
            return true;
        }