public sealed class Worker : BackgroundService { private readonly ILogger<Worker> _logger; private readonly IHostApplicationLifetime _hostApplicationLifetime; public Worker(ILogger<Worker> logger, IHostApplicationLifetime hostApplicationLifetime) { _logger = logger; _hostApplicationLifetime = hostApplicationLifetime; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { while (!stoppingToken.IsCancellationRequested) { try { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); string seconds = DateTimeOffset.Now.Second.ToString(); string hour = DateTimeOffset.Now.Hour.ToString(); string minute = DateTimeOffset.Now.Minute.ToString(); string day = DateTimeOffset.Now.Day.ToString(); string month = "0" + DateTimeOffset.Now.Month.ToString(); string year = DateTimeOffset.Now.Year.ToString(); string date = day + "_" + month + "_" + year; string startPath = @"D:\BackupProject"+"_"+date+"_"+hour+"_"+ minute+"_"+ seconds; string sourcePathNew = @"D:\BackupProject"; string targetPathNew = startPath; try { if (!Directory.Exists(startPath)) { Directory.CreateDirectory(startPath); CopyFilesRecursively(sourcePathNew, targetPathNew); } else { Directory.Delete(startPath, true); File.Delete(startPath + ".zip"); CopyFilesRecursively(sourcePathNew, targetPathNew); } } catch(Exception ex) { Console.WriteLine(ex.Message); } string zipPath = targetPathNew + ".zip".ToString(); ZipFile.CreateFromDirectory(startPath, zipPath); } catch (Exception ex) { _logger.LogError(ex, "Global exception occurred. Will resume in a moment."); } await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); } } //await Task.Delay(1000, stoppingToken); finally { _logger.LogCritical("Exiting application..."); //_hostApplicationLifetime.StopApplication(); } } public override Task StopAsync(CancellationToken cancellationToken) { return base.StopAsync(cancellationToken); } private static void CopyFilesRecursively(string sourcePath, string targetPath) { //Now Create all of the directories foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath)); } //Copy all the files & Replaces any files with the same name foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true); } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)