我正在閱讀一個簡單的文本文件,其中包含使用文件流類的單行。但它似乎filestream.read在一開始prepends一些垃圾字符。文件流預讀垃圾字符,同時閱讀
下面的代碼。
using (var _fs = File.Open(_idFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
byte[] b = new byte[_fs.Length];
UTF8Encoding temp = new UTF8Encoding(true);
while (_fs.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
Console.WriteLine(ASCIIEncoding.ASCII.GetString(b));
}
}
例如:我在文本文件中的數據僅僅是「樣品」。但上面的代碼返回
"?sample" and
"???sample"
是什麼原因?它是文件指示符的開始嗎?有沒有辦法只讀我的實際內容?
我在文本文件中的數據僅僅是「樣品」 < - 你肯定沒有它的UTF8 BOM盈?用十六進制編輯器檢查它。 – CodesInChaos 2010-11-13 10:12:49
@CodeInChaos,感謝提示,在十六進制編輯它看起來「ef bb bf 73 61 6d 70 6c 65 00 and ... sample」。這是爲什麼..... – RameshVel 2010-11-13 10:15:58
如果你需要去掉BOM,你已經做錯了。請參閱http://stackoverflow.com/questions/1317700/strip-byte-order-mark-from-string-in-c。 – 2010-11-13 10:17:42