StreamReader.ReadToEnd() returning an empty string

后端 未结 3 491
一向
一向 2020-12-17 18:00

I have a method

private static String DecompressAndDecode(byte[] data)
{
   GZipStream decompressor = new GZipStream(new MemoryStream(data), CompressionMode.         


        
相关标签:
3条回答
  • 2020-12-17 18:14

    I think your problem is the position of the pointer in the steam. Each time after you perform the ReadToEnd, the pointer is set to the end that is why you can watch it first time.

    Run the following code before ReadToEnd to set the pointer to the beginning. someStream.Seek(0, SeekOrigin.Begin)

    0 讨论(0)
  • 2020-12-17 18:14

    "There must be something obvious I'm missing here." - maybe, and so am I ;-)
    Let's start with a little self-contained example and see where it differs from your actual code.

    class SOTest
    {
      private static String DecompressAndDecode(byte[] data)
      {
        GZipStream decompressor = new GZipStream(new MemoryStream(data), CompressionMode.Decompress);
        StreamReader decompressed = new StreamReader(decompressor, Encoding.UTF8);
        String result = decompressed.ReadToEnd();
        return result;
      }
    
      private static byte[] foo(string data)
      {
        MemoryStream dest = new MemoryStream();
        using (GZipStream compressor = new GZipStream(dest, CompressionMode.Compress))
        {
          using (StreamWriter sw = new StreamWriter(compressor))
          {
            sw.Write(data);
          }
        }
        return dest.GetBuffer();
      }
    
    
      static void Main()
      {
        System.Console.WriteLine(
          DecompressAndDecode(foo("Mary had a little lamb."))
        );
        return;
      }
    }
    

    prints Mary had a little lamb.

    0 讨论(0)
  • 2020-12-17 18:28

    Create your own custom function. It'll take the path as a parameter:

        static string read(string path)
        {
            StreamReader sr = new StreamReader(@path); 
            string txt = "";
            while (!sr.EndOfStream) {
                txt += sr.ReadLine() + "\n";
            }
            sr.Close();
            return txt;
        }
    

    Then call it instead of the call to ReadToEnd(). I tested it, and it worked.

    0 讨论(0)
提交回复
热议问题