Considering a file named !file io test.txt
, containing the following lines:
1|adrian|louis|50000
2|jeff|potato|200000
3|michael|de santa|980000
4|jemmy|mccormic|500400
5|jack|cohen|4300000
6|ethan|trump|1080000
and considering this code segment:
FileStream fs = new FileStream(@"C:\Users\McLovin\Desktop\!file io test.txt", FileMode.Open, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
StreamReader sr = new StreamReader(fs);
char c = (char)sr.Read(); // line 4
sw.Write('~');
sw.Flush();
After line number 4, the file pointer should have read the first character and moved itself to the second one. This works as expected when I read the file, but when I write the file pointer, it always points to the end of the file and starts writing there. If I comment the line 4 out, the StreamWriter
will work as it should (overwrite the file from the beginning).
This current code produces:
1|adrian|louis|50000
2|jeff|potato|200000
3|michael|de santa|980000
4|jemmy|mccormic|500400
5|jack|cohen|4300000
6|ethan|trump|108000
~
but I want it to produce this:
1~adrian|louis|50000
2|jeff|potato|200000
3|michael|de santa|980000
4|jemmy|mccormic|500400
5|jack|cohen|4300000
6|ethan|trump|1080000
If you want to do it that way you'll need to reset the stream after the read.
numOfBytesRead = 1;
fs.Seek(numOfBytesRead, SeekOrigin.Begin);
I suspect the issue is with the internal buffer of the StreamReader. You get a single byte output but internally the reader has read ahead a bit to fill the buffer and leaves the position of the stream wherever it has actually read to.
The constructor overload you use results in a buffer size of 1024 bytes. The contents of your file is well below that so the position of the stream is left at the end after your read call. If you increase the size of your file beyond that you will see the tilde won't be written at the end anymore.
Interestingly enough it also looks like the buffer cannot be set below 128 bytes.