Why is my Stream not Readable?

强颜欢笑 提交于 2019-12-10 14:34:44

问题


This is a sequel to my question here about trimming the fat off a log file.

I have this code:

private readonly FileStream _fileStream;
private readonly StreamWriter _streamWriter;

. . .

    const int MAX_LINES_DESIRED = 1000;

    string uriPath = GetExecutionFolder() + "\\Application.log";
    string localPath = new Uri(uriPath).LocalPath;
    if (!File.Exists(localPath))
    {
        File.Create(localPath);
    }
    _fileStream = File.OpenWrite(localPath);
    // First, remove the earliest lines from the file if it's grown too much
    StreamReader reader = new StreamReader(_fileStream);
    . . .

Which fails on the last line shown with:

System.ArgumentException was unhandled
  _HResult=-2147024809
  _message=Stream was not readable.

Why is it not readable? I thought maybe because the file was empty, but I added a line to it, and still get the same err msg.


回答1:


File.OpenWrite creates a non-readable stream. If you're going to be reading and writing to the stream, you need to use File.Open(localPath, FileMode.Open, FileAccess.ReadWrite).

Additionally, you can just use FileMode.OpenOrCreate, and that will remove the need for your File.Exists conditional.




回答2:


The error code in hex is FFFFFFFF80070075 which equates to E_INVALIDARG - One or more arguments are invalid. See http://msdn.microsoft.com/en-us/library/cc704587.aspx for the definitions of the error codes.

Based on this, the stream not readable message, and looking at the code, it looks like the open call should specify the ReadWrite file access attribute on the call.



来源:https://stackoverflow.com/questions/27431351/why-is-my-stream-not-readable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!