How does StreamWriter class actually work?

时间:2016-04-04 17:47:16

标签: c# file-io filestream streamreader streamwriter

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

1 个答案:

答案 0 :(得分:0)

如果你想这样做,你需要在阅读后重置流。

numOfBytesRead = 1;
fs.Seek(numOfBytesRead, SeekOrigin.Begin); 

我怀疑问题出在 StreamReader 的内部缓冲区。你得到一个单字节输出,但在内部读者已经预读了一点来填充缓冲区并离开流实际读取的位置。

您使用的构造函数重载导致缓冲区大小为1024字节。您的文件内容远低于该值,因此在您的阅读通话结束后,流的位置将保留在最后。如果您将文件的大小增加到超过该值,您将看到不再在末尾写入波浪号。

有趣的是,它似乎也不能将缓冲区设置为低于128字节。