title: C# DeflateStream.Read() giving an InvalidDataException
body: <p>I want to unzip a compressed string so that the string of characters would become usable.</p>
  
  <p>I successfully extract in an array of bytes the content of a downloaded file with the function WebClient.DownloadData(String). </p>
  
  <p><em>The characters are logically compressed with the deflate method, because 7-Zip is giving this information when I download the file (in varying extensions) :</em></p>
  
  <p><a href="https://i.stack.imgur.com/njCBt.png" rel="nofollow noreferrer">Compressed file informations</a></p>
  
  <p>Thus, I am supposed to use the DeflateStream class to be able to decode the string, with the function Read(byte[] array, int offset, int count) ; reading a MemoryStream.</p>
  
  <p>I use a simple function which I can find online : </p>
  
  <pre><code>public string UnzipString2(byte[] byteArrayCompressedContent)
          {
              try
              {
                  using (var memoryStream = new MemoryStream())
                  {
                      int dataLength = BitConverter.ToInt32(byteArrayCompressedContent, 0);
                      memoryStream.Write(byteArrayCompressedContent, 4, byteArrayCompressedContent.Length - 4);
                      memoryStream.Position = 0;
  
                      var buffer = new byte[dataLength];
  
                      using (var deflateStream = new DeflateStream(memoryStream, System.IO.Compression.CompressionMode.Decompress))
                      {
                          deflateStream.Read(buffer, 0, buffer.Length);
                          deflateStream.Close();
                      }
                      return Encoding.UTF8.GetString(buffer);
                  }
              }
              catch (Exception e)
              {
                  return "";
              }
          }
  </code></pre>
  
  <p>When we call the Read() function, it is giving an InvalidDataException : Found in valid data while decoding ; with the stacktrace </p>
  
  <blockquote>
    <p>at System.IO.Compression.Inflater.DecodeDynamicBlockHeader()\r\n    at
    System.IO.Compression.Inflater.Decode()\r\n    at
    System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset,
    Int32 length)\r\n    at
    System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset,
    Int32 count)\r\n</p>
  </blockquote>
  
  <p>However, I still think that the information are compressed with the "deflate method".
  <strong>Is there a different/better/working way to read the data and decompress it in a String?</strong> </p>