Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 803
B. Clay Shannon-B. Crow Raven Avatar asked Dec 11 '14 19:12

B. Clay Shannon-B. Crow Raven


2 Answers

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.

like image 88
YtramX Avatar answered Nov 05 '22 08:11

YtramX


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.

like image 44
Rob Goodwin Avatar answered Nov 05 '22 08:11

Rob Goodwin