-1

I have SqlDatabase. In one column in database I have binary data, I checked and this is zip file. I downloaded this file with entity framework to byte[]. In this zip file I have always one single xml file. Now I want to extract this xml file from byte[] to byte[] or to string. Next I want to read this xml from string, byte[] and read one value. I don't know how to extract zip file from byte[] to byte[]/string.

Best regards

Marcin1199
  • 83
  • 1
  • 11
  • Did you google your problem? Did you do any research? Just google the last sentence of your "question" and add "c#". The first one is a [stackoverflow-article](http://stackoverflow.com/questions/12715945/unzip-a-memorystream-contains-the-zip-file-and-get-the-files) to which this question seems to be a duplicate. – Patrik Mar 30 '15 at 14:09
  • I was in this thread but I overlooked the built in solution. I remember that I saw DotNetZip, ziplib and icsharp. If possible I would like to use built in functions instead of external library. Yes, my thread is duplicate and the previous thread is better because of multiple solutions. I marked this thread as duplicate. – Marcin1199 Mar 31 '15 at 06:40

1 Answers1

1

In System.IO.Compression you will find all necessaire classes.

First decompress, using a method like this:

static byte[] Decompress(byte[] data)
{
    using (var compressedStream = new MemoryStream(data))
    using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
    using (var resultStream = new MemoryStream())
    {
        zipStream.CopyTo(resultStream);
        return resultStream.ToArray();
    }
}

Then, you can convert this array of bytes in a string, as you have a xml file. You can reach this using a code like this:

var str = System.Text.Encoding.Default.GetString(Decompress(byteArray));

You can also extract the file and then read it into a string.

Hope it helps.

Ricardo Pontual
  • 3,749
  • 3
  • 28
  • 43
  • Unfortunately with this solution I have exception about wrong magic number in header. – Marcin1199 Mar 31 '15 at 09:56
  • I realized that zip file inside database is "deflate". I tried with deflatestream from Ionic but I have exception about bad block size. In 7zip I can extract files without any problems. – Marcin1199 Mar 31 '15 at 10:29
  • I found that in specification of deflate there is no two first bytes "PK". I just skip it, and I didn't have exception but result stream is empty. – Marcin1199 Mar 31 '15 at 11:39