是否需要将流(C#)重新设置为开始? [英] Do I need to reset a stream(C#) back to the start?

查看:142
本文介绍了是否需要将流(C#)重新设置为开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#中的流了解不多。现在,我将一个流放入流阅读器中并进行阅读。稍后,在其他方法中,我需要读取流(相同的流对象),但是这一次出现此错误

I don't know too much about streams in C#. Right now I have a stream that I put into a stream reader and read it. Later on in some other method I need to read the stream(same stream object) but this time I get this error

System.ArgumentException was unhandled by user code
  Message="Stream was not readable."
  Source="mscorlib"
  StackTrace:
       at System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
       at System.IO.StreamReader..ctor(Stream stream)
       at ExtractTitle(Stream file) in :line 33
       at GrabWebPage(String webPath) in :line 62
       at lambda_method(ExecutionScope , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  InnerException: 

所以我想也许是通过阅读流到最后的流。然后,当我尝试再次阅读它时,它就在流的结尾,这就是为什么我收到此错误。

So I am thinking maybe by reading the stream it goes to the end. Then when I try to read it again it is at the end of the stream and thats why I am getting this error.

那么有人可以对此有所了解吗?

So can anyone shed some light on this?

谢谢

推荐答案

当您读完流时,特别是与 StreamReader ReadToEnd 方法,您必须 搜索 。可以这样完成:

When you read a stream to the end, specifically with StreamReader's ReadToEnd method, you have to Seek it back to the beginning. This can be done like so:

StreamReader sr = new StreamReader(stream);
sr.ReadToEnd();
stream.Seek(0, SeekOrigin.Begin); //StreamReader doesn't have the Seek method, stream does.
sr.ReadToEnd(); // This now works

这篇关于是否需要将流(C#)重新设置为开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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