Search code examples
c#memorystreamcompressiondeflate

How to decompress data from a memory stream in C#


I am trying to decompress a compressed base64 encoded string but have no idea how to do so. It is not a gzip and I am trying to decompress it without having to write to a file.


Solution

  • Tried suggestions from Unzip a memorystream (Contains the zip file) and get the files and finally found one that works with some changes made to use it as a method.

    public static string DecompressData(string val)
        {
            byte[] bytes = Convert.FromBase64String(val).ToArray();
            Stream data = new MemoryStream(bytes);
            Stream unzippedEntryStream;  
            MemoryStream ms = new MemoryStream();
            ZipArchive archive = new ZipArchive(data);
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                unzippedEntryStream = entry.Open();
                unzippedEntryStream.CopyTo(ms);  
            }
    
            string result = Encoding.UTF8.GetString(ms.ToArray());
            return result;
        }