Swapnil Patil
Swapnil Patil

Reputation: 156

Why StreamWriter can't access the closed stream but StreamReader can?

If I write following statements.

fileStream.Close();
reader.Close();
writer.Close();

reader.Close() statement executes successfully. But I get error "Can't open closed file." on 3rd statement writer.Close()

If I write

fileStream.Close();
writer.Close();
reader.Close();

2nd statement i.e. writer.Close() itself throws the same exception.

Does anyone have idea?

Upvotes: 1

Views: 2815

Answers (2)

Hans Passant
Hans Passant

Reputation: 942267

I'm going to have to guess that your code looks similar to do:

FileStream fileStream = new FileStream(...);
StreamWriter writer = new StreamWriter(fileStream);
...

Don't close fileStream, the stream writer now 'owns' the stream. Closing it closes the file stream as well.

Upvotes: 2

gordy
gordy

Reputation: 9806

I think it's because writer calls flush() before closing the underlying stream.

Upvotes: 5

Related Questions