Boardy
Boardy

Reputation: 36205

Reusing a stream after a method has completed

I am currently working on a C# project that uses a FileStream to open a file and passes the information to a StreamReader for it to be processed.

What I want to be able to do is I have a method which passes the stream to another method, that does the processing and once that method finishes, the original method calls another method passing it the same stream. However, when the first stream process completes when the second method is called it displays an exception saying that the thread is not readable.

When I look at debugging the stream, when I look at the details about the stream it says that it cannot be read, seek or write, and the length parameter of the stream says threw an exception of type System.ObjectDisposedException.

The question is, how can I keep the stream readable after the first method has completed so that the same stream can be processed in the second stream.

Thanks for any help you can provide.

Upvotes: 0

Views: 2319

Answers (2)

Marcin Deptuła
Marcin Deptuła

Reputation: 11957

If I understood you correctly, your stream is getting closed too fast. Based on what you say, it might be because you are Closing or Disposing StreamReader which, according to documentation, will close underlying stream.

Try not closing StreamReader (just ignore it, after it's not needed).

For example, if your code looks like this:

void P()
{
    var stream = new FileStream();
    P1(stream);
    P2(stream);
}

void P1(FileStream stream)
{
    using (var reader = new StreamReader(stream))
    {
      ......
    } //Here you would have disposed StreamReader and close FileStream
}


void P2(FileStream stream) // Stream is already closed
{
}

You have closed your stream in 1st method. You will have the same problem if you call:

  • reader.Dispose();
  • reader.Close();
  • stream.Dispose();
  • stream.Close();
  • using (stream);

So make sure aren't doing any of those things.

Btw: in C#5 I have heard, that Readers/Writers will be parametrized, if you want then to close underlying stream when they are closed (just like CryptoStream have right now)

Upvotes: -1

alexm
alexm

Reputation: 6882

if your streamReader is part of "using" statement, it disposes the file stream in the end of the statement block.

using (StreamReader reader = new StreamReader(fileStream))
{
      ..
}

Simple solution is not to dispose the reader explicitly, leaving it to GC

[More thoughts] If most of the methods are accessing file stream through TextReader interface, you can pass reader thus avoiding the problem with the ownership.

Upvotes: 4

Related Questions