V
V
Vyacheslav Bogatikov2015-05-02 19:59:19
.NET
Vyacheslav Bogatikov, 2015-05-02 19:59:19

How to rewrite a section of a file using streamwriter?

I know the position where the replacement needs to be done and I'm trying to write it like this:

_file = new FileStream(_filePath, FileMode.Create, FileAccess.Write);
_writer = new StreamWriter(_file);
//...
_writer.BaseStream.Seek(offset, SeekOrigin.Begin);
_writer.Write(size.Value);
_writer.BaseStream.Seek(currentPosition, SeekOrigin.Begin);

The position changes correctly, but _writer stubbornly writes to the end of the file.
What am I doing wrong?
PS At many forums such decision also was offered.
Example: stackoverflow.com/questions/8243122/how-to-write-d...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Bogatikov, 2015-05-02
@FunkEinstein

StreamWriter may have a documented, but unexpected behavior for me.
A dumb solution:

_writer.Flush();
_file.Seek(offset, SeekOrigin.Begin);
_writer = new StreamWriter(_file);

_writer.Write(size.Value);
_writer.Flush();

_file.Seek(currentPosition, SeekOrigin.Begin);
_writer = new StreamWriter(_file);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question