Why is my stream not being read?

This is a follow-up to my question here about trimming fat from 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 grown too much
    StreamReader reader = new StreamReader(_fileStream);
    . . .

      

What is failing in the last line shown with:

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

      

Why can't you read it? I thought maybe because the file was empty, but I added a line to it and still get the same message number.

+3


source to share


2 answers


File.OpenWrite

creates an unreadable stream. If you are going to read and write to a stream, you need to use File.Open(localPath, FileMode.Open, FileAccess.ReadWrite)

.



Alternatively, you can just use FileMode.OpenOrCreate

and that will remove the need for your File.Exists

conditional.

+4


source


The error code in hex is FFFFFFFF80070075

equal to E_INVALIDARG - One or more arguments are invalid

. See http://msdn.microsoft.com/en-us/library/cc704587.aspx for error codes definition.



Based on this streaming unreadable message and looking at the code, it looks like the open call should specify the ReadWrite file access attribute when called.

+1


source







All Articles