Script Backup Tool

This is a C# console application that allows users to backup their C# scripts from a specified source directory to a destination directory. The application first prompts the user to enter the source and destination drive letters, and uses default values if the user does not provide any input. It then checks whether there is enough free space on the destination drive and prompts the user to confirm whether they want to continue with the backup. The application then scans the source directory for all C# script files (with the ".cs" extension) and copies them to the destination directory. It excludes any files within a specified "MyProjects" folder within the source directory. If a file already exists in the destination directory, the user is prompted whether they want to overwrite the file or skip it. The application logs any errors encountered during the backup process to a "ScriptsBackupError.log" file in the destination directory. The progress of the backup is displayed to the user in terms of the number of files processed and the percentage of the backup that is complete. Once the backup is complete, the application displays a message indicating that the backup has finished. -------------------------------------------------------------------------------------------------------------------------------
 
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

namespace ScriptsBackup
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the C# ScriptsBackup Tool");
            Console.WriteLine("-------------------------------------");

            string defaultSourceDriveLetter = "D";
            string defaultDestinationDriveLetter = "F";

            Console.Write($"Enter the source drive letter (default: '{defaultSourceDriveLetter}'): ");
            string sourceDriveLetter = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(sourceDriveLetter))
            {
                sourceDriveLetter = defaultSourceDriveLetter;
            }
            string sourceDirectory = $@"{sourceDriveLetter}:\";

            Console.Write($"Enter the destination drive letter (default: '{defaultDestinationDriveLetter}'): ");
            string destinationDriveLetter = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(destinationDriveLetter))
            {
                destinationDriveLetter = defaultDestinationDriveLetter;
            }
            string destinationDirectory = $@"{destinationDriveLetter}:\ScriptsBackup";

            long requiredFreeSpace = 1L * 1024 * 1024 * 1024; // 1GB
            long availableFreeSpace = GetAvailableFreeSpace(destinationDriveLetter);

            if (availableFreeSpace < requiredFreeSpace)
            {
                Console.WriteLine($"Not enough free space on the target drive. You need at least 1GB of free space.");
                return;
            }

            Console.WriteLine($"Source: {sourceDirectory}");
            Console.WriteLine($"Destination: {destinationDirectory}");
            Console.Write("Do you want to continue? (Y/N): ");
            string userInput = Console.ReadLine();

            if (userInput.Equals("N", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("Operation cancelled by the user.");
                return;
            }

            if (!Directory.Exists(destinationDirectory))
            {
                Directory.CreateDirectory(destinationDirectory);
            }

            Console.WriteLine("Scanning your drive for files to backup...");
            ScanAndCopyScripts(sourceDirectory, destinationDirectory);
        }

        private static void LogError(string destinationDirectory, string message)
        {
            string logFilePath = Path.Combine(destinationDirectory, "ScriptsBackupError.log");
            using (StreamWriter writer = new StreamWriter(logFilePath, true))
            {
                writer.WriteLine($"{DateTime.Now}: {message}");
            }
        }

        private static long GetAvailableFreeSpace(string driveLetter)
        {
            DriveInfo driveInfo = new DriveInfo(driveLetter);
            return driveInfo.AvailableFreeSpace;
        }

        private static string[] GetCSharpFiles(string directory)
        {
            var cSharpFiles = new List();
            var subdirectoriesToProcess = new Stack();

            subdirectoriesToProcess.Push(directory);

            while (subdirectoriesToProcess.Count > 0)
            {
                string currentDirectory = subdirectoriesToProcess.Pop();

                try
                {
                    cSharpFiles.AddRange(Directory.GetFiles(currentDirectory, "*.cs"));
                    foreach (string subdirectory in Directory.GetDirectories(currentDirectory))
                    {
                        subdirectoriesToProcess.Push(subdirectory);
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    Console.WriteLine($"Access denied: Unable to scan {currentDirectory}. Skipping.");
                }
            }

            return cSharpFiles.ToArray();
        }

        private static void ScanAndCopyScripts(string sourceDirectory, string destinationDirectory)
        {
            string[] cSharpFiles = GetCSharpFiles(sourceDirectory);
            string excludedFolder = Path.Combine(sourceDirectory, "MyProjects");

            // Filter out files within the excluded folder
            cSharpFiles = cSharpFiles.Where(file => !file.StartsWith(excludedFolder, StringComparison.OrdinalIgnoreCase)).ToArray();

            Console.WriteLine("C# scripts found: " + cSharpFiles.Length);

            bool overwriteAll = false;
            bool askEachTime = true;

            int totalFiles = cSharpFiles.Length;
            int filesProcessed = 0;

            foreach (string filePath in cSharpFiles)
            {
                string destinationPath = Path.Combine(destinationDirectory, Path.GetRelativePath(sourceDirectory, filePath));

                string directoryPath = Path.GetDirectoryName(destinationPath);
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }

                if (File.Exists(destinationPath))
                {
                    if (askEachTime)
                    {
                        Console.Write($"File {destinationPath} already exists. Do you want to overwrite? (Y/N/All): ");
                        string input = Console.ReadLine();

                        if (input.Equals("All", StringComparison.OrdinalIgnoreCase))
                        {
                            overwriteAll = true;
                            askEachTime = false;
                        }
                        else if (!input.Equals("Y", StringComparison.OrdinalIgnoreCase))
                        {
                            filesProcessed++;
                            DisplayProgress(filesProcessed, totalFiles);
                            continue;
                        }
                    }
                }

                try
                {
                    if (overwriteAll || !File.Exists(destinationPath))
                    {
                        File.Copy(filePath, destinationPath, true);
                        Console.WriteLine($"Copied: {filePath} -> {destinationPath}");
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    Console.WriteLine($"Access denied: Unable to copy {filePath}. Skipping.");
                }
                filesProcessed++;
                DisplayProgress(filesProcessed, totalFiles);
            }

            Console.WriteLine("Backup completed.");
        }

        private static void DisplayProgress(int filesProcessed, int totalFiles)
        {
            double percentage = ((double)filesProcessed / totalFiles) * 100;
            Console.WriteLine($"Progress: {filesProcessed}/{totalFiles} ({percentage:0.00}%)");
        }
    }
}


 

Comments

Popular posts from this blog

Clone Command Bar Button in Model Driven App: Order & OrderDetails

Model-Driven Apps: Modern Command Bar Customization

Knowledge shared is power squared!