我是否需要将流(C#)重置为开头?

cho*_*bo2 40 .net c#

我不太了解C#中的流.现在我有一个流放入流阅读器并阅读它.稍后在其他一些方法中我需要读取流(相同的流对象),但这次我得到了这个错误

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: 
Run Code Online (Sandbox Code Playgroud)

所以我想也许是通过阅读流程到最后.然后,当我尝试再次读取它时,它位于流的末尾,这就是为什么我收到此错误.

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

谢谢

小智 70

当你读到流到底,特别是与StreamReaderReadToEnd方法,你要Seek它回到起点.这可以这样做:

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
Run Code Online (Sandbox Code Playgroud)

  • 语法稍微简单:`stream.Position = 0;` (8认同)
  • 这看起来比只关闭它更好的方法,看起来像是正确的答案.+1 (3认同)

Mic*_*tta 32

你的结论是正确的; 一旦到达流的末尾,在重置流中的位置之前,您将无法读取更多数据:

myStream.Position = 0;
Run Code Online (Sandbox Code Playgroud)

这相当于回到起点.请注意,您的流必须支持寻求此工作; 不是所有的流都可以.您可以使用CanSeek酒店查询.


小智 5

用于:BaseStreamStreamReader

 StreamReader sr = new StreamReader(pFileStream);
 sr.BaseStream.Seek(0, SeekOrigin.Begin);
Run Code Online (Sandbox Code Playgroud)