string filePath = "C:\\1.txt";
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[100];
fs.Position = 0;
fs.Read(bytes, 0, 100);
Console.Write(Encoding.UTF8.GetString(bytes));
fs.Close();文本是:周末想去买款联想thinkpad笔记本,不知珠江路哪家店比较好,希望大家给点意见 ^-^,谢谢!
读出来的是:?周末想去买款联想thinkpad笔记本,不知珠江路哪家店比较好,希望大家给?为什么第一个字符会读错?
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[100];
fs.Position = 0;
fs.Read(bytes, 0, 100);
Console.Write(Encoding.UTF8.GetString(bytes));
fs.Close();文本是:周末想去买款联想thinkpad笔记本,不知珠江路哪家店比较好,希望大家给点意见 ^-^,谢谢!
读出来的是:?周末想去买款联想thinkpad笔记本,不知珠江路哪家店比较好,希望大家给?为什么第一个字符会读错?
using (StreamReader sr = new StreamReader(filename, Encoding.Default))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
//tempstring = tempstring + line;
//判断读取的数据是不是有效
line = line.Trim();
if (line.Length > 0)
{
// temp=Encoding.GetEncoding(line).ToString();
if (ser == l)
{
tempstring = line;
break;
}
l++;
}
}
sr.Close();
return tempstring;
}
byte[100]限定产生的错误
这100里可以有占一个字节的控制符号 或者字母 导致头尾 都只有半个汉字
fs.Read(bytes, 0, 100);
这里别用100,
改成:
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);试试
我写的是这样。。不会出现你那样的问题呀
FE FF UTF-16/UCS-2, little endian
FF FE UTF-16/UCS-2, big endian
FF FE 00 00 UTF-32/UCS-4, little endian.
为了更方便区分ANSI和utf8格式文本文件,微软会偷偷在utf8格式文本文件前加个特殊字符做标记,你读出的就是那个字符了。
public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
如果指定detectEncodingFromByteOrderMarks为true,StreamReader会自动帮你忽略掉那个特殊的BOM字符。
如果调用public StreamReader(string path);则实际上调用的是StreamReader(path, Encoding.UTF8, true, 0x400)。