Opening a file for both read/write

G

Guest

In C I can open a file as readable, writable, or both. Then I can
arbitrarily do either operation without closing the file between operations
as long as I perform some kind of file position indicator repositioning when
I change between reading and writing. In C# I'd like something like a
StreamReaderWriter that I could use the same way, but there doesn't appear to
be such a thing. I don't want to have to repeatedly close, reopen, and
reseek since I in my application I would have to do this for each byte that I
write. Is it possible to open the same file with both a StreamReader and a
StreamWriter simultaneously?

Thanks!
Ray
 
N

Nicholas Paldino [.NET/C# MVP]

Ray,

Assuming that you were holding a reference to the underlying FileStream
(or, you used the BaseStream property on the StreamReader or StreamWriter
class), you could have a StreamReader/StreamWriter open at the same time.
You would have to call Flush on the StreamWriter, to flush any buffered data
to the underlying stream, and then call DiscardBufferedData on the
StreamReader, to discard any data that the reader buffered. Then, you could
seek on the file stream, and you should be able to use the
StreamReader/StreamWriter again.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Ray Mitchell said:
In C I can open a file as readable, writable, or both. Then I can
arbitrarily do either operation without closing the file between
operations
as long as I perform some kind of file position indicator repositioning
when
I change between reading and writing. In C# I'd like something like a
StreamReaderWriter that I could use the same way, but there doesn't appear
to
be such a thing. I don't want to have to repeatedly close, reopen, and
reseek since I in my application I would have to do this for each byte
that I
write. Is it possible to open the same file with both a StreamReader and
a
StreamWriter simultaneously?

Use FileStream
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top