zip function working but caught error saying the zip folder already existed

3425 views c#
4

I have a simple zip function and using a timer to delay the zip process once a new folder created. I always got an error message saying the zip folder exist although has the timestamp to distinguish each zip folder name. Below is my code,

public static void CompressData()
       {
            var basePath = @"D:\Documents\C#\output";
        // Returns subdirectories(including their paths) in the specified directory.
        var directories = Directory.GetDirectories(basePath);

        try
        {
            foreach (var dir in directories)
            {
                //Console.WriteLine(dir);

                var folderToBeZipped = dir;
                // Get sub folder content
                var subdir = new DirectoryInfo(dir);
                var zipPath = $@"{basePath}\{subdir.Name}-{ DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss")}.zip";
                //var zipPath = $@"{basePath}\{subdir.Name}.zip";

                using (ZipArchive zip = ZipFile.Open(zipPath, ZipArchiveMode.Create))
                {
                    // zip the folder
                    ZipFile.CreateFromDirectory(folderToBeZipped, zipPath, CompressionLevel.Optimal, true);

                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("err reason: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("time up spooling, zipping file...");
        }

static void SetTimer()
        {
            // once detect file move in, use timer to set time interval before start zip
            // and then reset timer
            System.Timers.Timer aTimer = new System.Timers.Timer();
            aTimer.Interval = 5000;
            aTimer.Elapsed += new ElapsedEventHandler(ZipEvent);
            aTimer.Enabled = true;
            aTimer.AutoReset = false; //false if it should raise the Elapsed event only once
        }

        static void ZipEvent(object sender, ElapsedEventArgs e)
        {
            CompressData();                      
        }

answered question

1 Answer

0

You are creating the zip-file twice, so just delete this line:

using (ZipArchive zip = ZipFile.Open(zipPath, ZipArchiveMode.Create))

You are creating it again in the next line:

ZipFile.CreateFromDirectory(folderToBeZipped, zipPath, CompressionLevel.Optimal, true);

posted this

Have an answer?

JD

Please login first before posting an answer.