Progress Bar not available for zipfile? How to give feedback when program seems to hang

后端 未结 2 445
忘了有多久
忘了有多久 2020-12-03 12:52

I am fairly new to C# and coding in general so some of this might be going about things the wrong way. The program I wrote works and compresses the file as expected, but if

2条回答
  •  悲&欢浪女
    2020-12-03 13:34

    Using ZipFile.CreateFromDirectory you can create a kind of progress based on the size of the output file. Using the compression in another thread (Task.Run) you should be able to update your UI and make it responsive.

    void CompressFolder(string folder, string targetFilename)
    {
        bool zipping = true;
        long size = Directory.GetFiles(folder).Select(o => new FileInfo(o).Length).Aggregate((a, b) => a + b);
    
        Task.Run(() =>
        {
            ZipFile.CreateFromDirectory(folder, targetFilename, CompressionLevel.NoCompression, false);
            zipping = false;
        });
    
        while (zipping)
        {
            if (File.Exists(targetFilename))
            {
                var fi = new FileInfo(targetFilename);
                System.Diagnostics.Debug.WriteLine($"Zip progress: {fi.Length}/{size}");
            }
        }
    }
    

    This works 100% if you have CompressionLevel to NoCompression. With compression it would work partly based on the ending size of the zip file. But it will show that something is happening, so when the file is done, jump from whatever percentage of progress to 100%.

提交回复
热议问题