Question: I know this question has been asked before on Stackoverflow, but could not find an explanation.

When I try to read a string from a compressed byte array I get an empty string on the first attempt, on the second I succed and get the string.

Code example:

```
public static string Decompress(byte[] gzBuffer)
{
    if (gzBuffer == null)
        return null;
    using (var ms = new MemoryStream(gzBuffer))
    {
        using (var decompress = new GZipStream(ms, CompressionMode.Decompress))
        {
            using (var sr = new StreamReader(decompress, Encoding.UTF8))
            {
                string ret = sr.ReadToEnd();
                // this is the extra check that is needed !?
                if (ret == "")
                    ret = sr.ReadToEnd();
                return ret;
            }
        }
    }
}

```

All suggestions are appreciated. 
- Victor Cassel

Answer: 
try adding `ms.Position = 0` before `string ret = sr.ReadToEnd();`
I hope this helps.

For ByteArray:

```
static byte[] CompressToByte(string data)
{
    MemoryStream outstream = new MemoryStream();
    GZipStream compressionStream =
    new GZipStream(outstream, CompressionMode.Compress, true);
    StreamWriter writer = new StreamWriter(compressionStream);
    writer.Write(data);
    writer.Close();
    return StreamToByte(outstream);
}

static string Decompress(byte[] data)
{
    MemoryStream instream = new MemoryStream(data);
    GZipStream compressionStream =
    new GZipStream(instream, CompressionMode.Decompress);
    StreamReader reader = new StreamReader(compressionStream);
    string outtext = reader.ReadToEnd();
    reader.Close();
    return outtext;
}

public static byte[] StreamToByte(Stream stream)
{
    stream.Position = 0;
    byte[] buffer = new byte[128];
    using (MemoryStream ms = new MemoryStream())
    {
        while (true)
        {
            int read = stream.Read(buffer, 0, buffer.Length);
            if (!(read > 0))
                return ms.ToArray();
            ms.Write(buffer, 0, read);
        }
    }
}
```

You can replace `if(!(read > 0))` with `if(read <= 0)`.
For some reason `if(read <= 0)` isn't displayed corret above.

For Stream:

```
static Stream CompressToStream(string data)
{
    MemoryStream outstream = new MemoryStream();
    GZipStream compressionStream =
    new GZipStream(outstream, CompressionMode.Compress, true);
    StreamWriter writer = new StreamWriter(compressionStream);
    writer.Write(data);
    writer.Close();
    return outstream;
}

static string Decompress(Stream data)
{
    data.Position = 0;
    GZipStream compressionStream =
    new GZipStream(data, CompressionMode.Decompress);
    StreamReader reader = new StreamReader(compressionStream);
    string outtext = reader.ReadToEnd();
    reader.Close();
    return outtext;
}
```