Search code examples
c#streamstringwriter

Why StringWriter.ToString return `System.Byte[]` and not the data?


UnZipFile method writes the data from inputStream to outputWriter. Why sr.ToString() returns System.Byte[] and not the data?

using (var sr = new StringWriter())
{
    UnZipFile(response.GetResponseStream(), sr);
    var content = sr.ToString();
}


public static void UnZipFile(Stream inputStream, TextWriter outputWriter)
{
    using (var zipStream = new ZipInputStream(inputStream))
    {
        ZipEntry currentEntry;
        if ((currentEntry = zipStream.GetNextEntry()) != null)
        {
            var size = 2048;
            var data = new byte[size];
            while (true)
            {
                size = zipStream.Read(data, 0, size);
                if (size > 0)
                {
                    outputWriter.Write(data);                       
                }
                else
                {
                    break;
                }
            }
        }
    }
}

Solution

  • The problem is on the line:

    outputWriter.Write(data); 
    

    StringWriter.Write has no overload expecting a byte[]. Therefore, Write(Object) is called instead. And according to MSDN:

    Writes the text representation of an object to the text string or stream by calling the ToString method on that object.

    Calling ToString on a byte array returns System.byte[], explaining how you get that string in your StringWriter.