Frage

I have 5 MemoryStreams. I want to create a new zip (Which will also be a Stream) while each of the 5 MemoryStreams I have, will respresnt a file.

I do have this code about how to Zip a string/1 MemoryStream.

public static string Zip(string value)
{
    //Transform string into byte[]  
    byte[] byteArray = new byte[value.Length];
    int indexBA = 0;
    foreach (char item in value.ToCharArray())
    {
        byteArray[indexBA++] = (byte)item;
    }

    //Prepare for compress
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
        System.IO.Compression.CompressionMode.Compress);

    //Compress
    sw.Write(byteArray, 0, byteArray.Length);
    //Close, DO NOT FLUSH cause bytes will go missing...
    sw.Close();

    //Transform byte[] zip data to string
    byteArray = ms.ToArray();
    System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
    foreach (byte item in byteArray)
    {
        sB.Append((char)item);
    }
    ms.Close();
    sw.Dispose();
    ms.Dispose();
    return sB.ToString();
}

This code is good, But I need some kind of separation between the MemoryStreams. I don't want them to be consecutive. (Preferably I'd like them to be on different files within the ZipStream)

How can I create files (or a similar separator) within the ZipStream?

War es hilfreich?

Lösung

GZipStream in the .net library is not really geared up for creating zip files. It's main purpose is to compress a stream which could be for sending data or in your example above streaming to a file.

Compressed GZipStream objects written to a file with an extension of .gz can be decompressed using many common compression tools; however, this class does not inherently provide functionality for adding files to or extracting files from .zip archives.

You can get the GZip library to create a zip file with multiple compressed files but it will require some legwork on your part. There is a blog post here that shows you how to do it.

However there are some other solutions you could consider:

  1. SharpZipLib is a free and widely used compression library. The link provided is to the wiki which shows you how to compress and decompress. You can de/compress from and to files or streams.
  2. .net 3 has a packaging library which you could look at. One thing to note is it will contain meta data. Also this library cannot open zip files which do not contain the meta data. The link provided has an example at the bottom on how to compress multiple files.
  3. There are other libraries out that are free but I have not used them.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top