【发布时间】:2015-02-02 15:13:16
【问题描述】:
我在读取文件的同时打开了一个StreamWriter 文件,这似乎导致了问题(这是一组较大代码中的一个较小的 sn-p,只是为了说明我的问题):
static void Main(string[] args)
{
for (int i = 0; i < 3; i++)
{
using (FileStream stream = new FileStream("file.txt", FileMode.OpenOrCreate))
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, 0x1000, true))
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8, 0x1000, true))
{
Console.WriteLine("Read \"" + reader.ReadToEnd() + "\" from the file.");
}
}
Console.ReadLine();
}
上面的代码会输出:
Read "" from the file.
Read "" from the file.
Read "?" from the file.
如果文件已经包含一些文本,编写器会将 BOM 附加到末尾,尽管从未被调用写入任何内容:
Read "TEXT" from the file.
Read "TEXT?" from the file.
Read "TEXT??" from the file.
为什么会出现这种行为?
【问题讨论】:
-
@grovesNL 这是关于 StreamReader,而不是关于 GetString,这些答案对我没有帮助。
-
@grovesNL 即使它是 BOM 值,我会惊讶地看到它在结尾而不是开头...
-
@Alexandru 如果 BOM (0xFEFF) 一开始就与 StreamReader 有关。因为这...可能您的文件刚刚损坏。
-
在同一个流上拥有一个阅读器和一个作者通常不是一个好主意...
标签: c# .net io stream streamreader