我有一個StreamWriter
在我讀取它的同時打開我的文件,這似乎是導致問題的原因(這是更大的一組代碼中的一個較小片段,只是以說明我的問題):StreamWriter正在將BOM字符65279附加到文件結尾
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.
它爲什麼會表現出這種行爲?
可能的重複[如何忽略字符串比較中的UTF-8字節順序標記?](http://stackoverflow.com/questions/2915182/how-do-i-ignore-the-utf-8-字節順序標記在字符串比較) – grovesNL 2014-12-04 16:35:39
@grovesNL這是關於StreamReader,而不是關於GetString,這些答案不幫助我。 – Alexandru 2014-12-04 16:41:51
@grovesNL即使它的BOM值我會很驚訝地看到**在最後**而不是開始... – 2014-12-04 16:41:59