我对C#中的streams了解不多。现在我有一个流,我将其放入流阅读器中并读取它。稍后,在其他一些方法中,我需要读取流(相同的流对象),但这次我得到了这个错误
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: 所以我在想,也许通过读这条流,它就会走到尽头。然后,当我再次尝试读取它时,它位于流的末尾,这就是为什么我得到这个错误的原因。
那么,有没有人能对此有所了解?
谢谢
发布于 2009-11-17 09:52:51
当你读到一个流的结尾时,特别是使用StreamReader的ReadToEnd方法,你必须把它读回开头。这可以这样做:
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发布于 2009-11-17 09:53:10
您的结论是正确的;一旦到达流的末尾,在重新设置流中的位置之前,您将无法读取更多数据:
myStream.Position = 0;这相当于回到起点。请注意,您的流必须支持查找才能工作;并不是所有的流都支持。您可以使用CanSeek属性检查这一点。
发布于 2015-07-08 02:19:15
为StreamReader使用BaseStream
StreamReader sr = new StreamReader(pFileStream);
sr.BaseStream.Seek(0, SeekOrigin.Begin);https://stackoverflow.com/questions/1746092
复制相似问题