StreamReader.ReadToEnd()返回一个空字符串 [英] StreamReader.ReadToEnd() returning an empty string

查看:829
本文介绍了StreamReader.ReadToEnd()返回一个空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法

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;
}

我有一些GZipped文本作为输入,结果应该是字符串此文本的表示形式。问题在于该方法返回一个空字符串。令我感到困惑的是,当我在调试模式下通过方法并到达return语句时,结果变量是一个空字符串,但是如果我创建了decompressed.ReadToEnd()表达式的监视程序,它将返回文本。我现在期望的是结果变量包含文本和评估为空字符串的decompressed.ReadToEnd()表达式。 (重新评估decompressed.ReadToEnd()表达式将按预期返回空字符串。)

I have some GZipped text as input and the result is supposed to be a String representation of this text. The problem is that the method returns an empty string. What is puzzling me is that when I step trough the method in debug mode and reach the return statement the result variable is an empty string but if I create a watch for the decompressed.ReadToEnd() expression it returns me the text. What I would expect at this point is the result variable to contain the text and the decompressed.ReadToEnd() expression evaluating to an empty string. (Reevaluating the decompressed.ReadToEnd() expression returns an empty string as expected).

@Edit:我发现在我的情况 ReadToEnd()在第二次调用时返回文本 在第一次调用时以及第二次调用后返回空字符串。

@ I have found that in my case ReadToEnd() returns the text on the second call returning empty strings on the first call and after the second call.

这里肯定缺少一些明显的东西。

There must be something obvious I'm missing here.

推荐答案

我认为您的问题是指针在蒸汽中的位置。每次执行 ReadToEnd 后,指针都设置到结尾,这就是为什么您可以第一次观看它的原因。

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.

ReadToEnd 之前运行以下代码,将指针设置为开头。
someStream.Seek(0,SeekOrigin.Begin)

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

这篇关于StreamReader.ReadToEnd()返回一个空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆