How to compress an existing file using the ZipArchive class in this way creates an archive, but it is empty.

ZipFile.CreateFromDirectory(@"C:\123.txt", @"C:\12313.zip") 

Or I did not understand the meaning of the parameters? As I understood the first parameter, we set the file that we want to compress, the second parameter is the name of the archive and its path where the file will be compressed

    2 answers 2

    The ZipFile class ZipFile -unpacks an entire folder at once.

    If you need to pack a separate file, use the ZipArchive class. Example:

     string path = @"C:\123.txt"; string filename = Path.GetFileName(path); using (var dest = new FileStream(@"C:\12313.zip", FileMode.Create)) using (var archive = new ZipArchive(dest, ZipArchiveMode.Create)) using (var source = new FileStream(path, FileMode.Open)) { ZipArchiveEntry entry = archive.CreateEntry(filename); byte[] bytes = new byte[source.Length]; source.Read(bytes, 0, bytes.Length); using (var stream = entry.Open()) stream.Write(bytes, 0, bytes.Length); } 

      I use the DotNetZip library for this purpose .

      Then an archive from a specific directory can be created like this:

        using (ZipFile zip = new ZipFile()) { zip.AddDirectory(@"MyDocuments\ProjectX", "ProjectX"); zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ; zip.Save(zipFileToCreate); } 

      Regarding the code from the question: Does it bother you that the method is called CreateFromDirectory , but pass the file as the first argument?

      • That is, it is all from the directory, not the file separately - test19