skip to Main Content

I’m writing a web app ,it can upload/download files, here is my code about download files(just for test):

    static void Main(string[] args)
    {
        var zipName = $"archive-{DateTime.Now:yyyy_MM_dd-HH_mm_ss}.zip";
        var folder = "D:\xxdd";
        using var memoryStream = new MemoryStream();
        using var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);
        var files = Directory.GetFiles(folder);
        foreach (var file in files)
        {
            zipArchive.CreateEntryFromFile(file, Path.GetFileName(file));
        }
        
        memoryStream.Position = 0;
        File.WriteAllBytes(zipName,memoryStream.ToArray());
        Console.WriteLine("Hello, World!");
    }

when I opened the zip file, it said the zip is empty, then I dragged it into the bandizip,it said the file was broken,but all the files were in the list and it could be unzip.
how to fix it ?
enter image description here

enter image description here

2

Answers


  1. Try this,

    static void Main(string[] args)
    {
        var zipName = $"archive-{DateTime.Now:yyyy_MM_dd-HH_mm_ss}.zip";
        var folder = "D:\xxdd";
        
        using (var fileStream = File.Create(zipName))
        using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
        {
            var files = Directory.GetFiles(folder);
            foreach (var file in files)
            {
                zipArchive.CreateEntryFromFile(file, Path.GetFileName(file));
            }
        }
        
        Console.WriteLine("Hello, World!");
    }
    
    1. Put the ZipArchive in a separate using block to ensure it’s properly
      disposed before writing.
    2. The ZipArchive needs to be disposed to finalize the ZIP file
      structure.
    3. After disposal, the memoryStream contains the complete ZIP file
      data.
    Login or Signup to reply.
  2. You don’t call Dispose on the ZipArchive, so the data isn’t completely written. As the documentation says:

    "This method finishes writing the archive and releases all resources used by the ZipArchive object."

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search