Search code examples
c#file-iourifilestreamstreamreader

Why is my Stream not Readable?


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.


Solution

  • 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.