Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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);
            }
        }
    }


What I have tried:

I Tried it, Its working, Is it correct way to auto backup a folder?
Posted
Updated 30-Apr-22 3:56am

1 solution

If it works, it works. Make a working sample and then work on it to improve the enhancements.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900