0

I'm trying to convert this java snippet code in c# but I'm a bit confused about it. This is the java code:

My try is the following, but there are some errors in gis.Read, because it wants a char* and not a byte[] and in the String constructor for the same reason.

public static String decompress(InputStream input) throws IOException 
{
    final int BUFFER_SIZE = 32;
    GZIPInputStream gis = new GZIPInputStream(input, BUFFER_SIZE);
    StringBuilder string = new StringBuilder();
    byte[] data = new byte[BUFFER_SIZE];
    int bytesRead;
    while ((bytesRead = gis.read(data)) != -1) {
        string.append(new String(data, 0, bytesRead));
    }
    gis.close();
    // is.close();
    return string.toString();
}

I expected to get a readable string.

Roberto Pegoraro
  • 1,313
  • 2
  • 16
  • 31
Giuseppe Pennisi
  • 396
  • 3
  • 22
  • https://stackoverflow.com/questions/1003275/how-to-convert-utf-8-byte-to-string – vasily.sib Jun 28 '19 at 08:53
  • GZipStream Read method works with bytes. Check [docs](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.gzipstream.read?view=netframework-4.8) – Aleks Andreev Jun 28 '19 at 08:55

1 Answers1

2

You need to transform the bytes to characters first. For that, you need to know the encoding.

In your code, you could have replaced new String(data, 0, bytesRead) with Encoding.UTF8.GetString(data, 0, bytesRead) to do that. However, I would handle this slightly differently.

StreamReader is a useful class to read bytes as text in C#. Just wrap it around your GZipStream and let it do its magic.

public static string Decompress(Stream input)
{
    // note this buffer size is REALLY small. 
    // You could stick with the default buffer size of the StreamReader (1024)
    const int BUFFER_SIZE = 32;
    string result = null;
    using (var gis = new GZipStream(input, CompressionMode.Decompress, leaveOpen: true))
    using (var reader = new StreamReader(gis, Encoding.UTF8, true, BUFFER_SIZE))
    {
        result = reader.ReadToEnd();
    }

    return result;
}
Jesse de Wit
  • 3,867
  • 1
  • 20
  • 41
  • Thanks for the answer. To do a complete magic i used another GZipStream's constructor: new GzipStrem(input, CompressionMode.Decompress) that's because i need to decompress the stream, not to compress. So if you want, please modify your answer to help other people with this problem. Thanks Again. – Giuseppe Pennisi Jul 03 '19 at 07:57