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笔记本,不知珠江路哪家店比较好,希望大家给?为什么第一个字符会读错?

解决方案 »

  1.   

    用StreamReader 呢
      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;
                        }
      

  2.   

    读取一行应该就没有问题了
    byte[100]限定产生的错误
    这100里可以有占一个字节的控制符号 或者字母 导致头尾 都只有半个汉字
      

  3.   

    byte[] bytes = new byte[100];
    fs.Read(bytes, 0, 100);
    这里别用100,
    改成:
    byte[] bytes = new byte[fs.Length];
    fs.Read(bytes, 0, bytes.Length);试试
      

  4.   

    FileStream fs = new FileStream(myfilename, FileMode.Open, FileAccess.Read);
    我写的是这样。。不会出现你那样的问题呀
      

  5.   

    文件头那个诡异的无法显示的字符只是标识这个文本是一个UTF8格式
      

  6.   

    EF BB BF UTF-8
    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.
      

  7.   

    那为什么用StreamReader类来读取就没了这个“?”?
      

  8.   

    用StreamReader就不会错了,如果还会错,那就是你写入文件时候的编码和读的时候不一样,
      

  9.   

    那为什么StreamReader和文件流会有这个不同?
      

  10.   

    你读的应该是一个utf8文件。
    为了更方便区分ANSI和utf8格式文本文件,微软会偷偷在utf8格式文本文件前加个特殊字符做标记,你读出的就是那个字符了。
      

  11.   

    那为什么用StreamReader就没有了?
      

  12.   

    看看你读到的前2个字节是不是FF EF?
      

  13.   

    StreamReader有一个构建方法:
    public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
    如果指定detectEncodingFromByteOrderMarks为true,StreamReader会自动帮你忽略掉那个特殊的BOM字符。
    如果调用public StreamReader(string path);则实际上调用的是StreamReader(path, Encoding.UTF8, true, 0x400)。