我想把txt文档读到一个textbox中显示,按一下左右键翻页,和小说阅读器差不多。但是遇到几个问题。
先上代码
private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                strPath = ConfigurationManager.AppSettings["path"];
                book = Convert.ToInt32(ConfigurationManager.AppSettings["book"]);
                FileInfo fi = new FileInfo(strPath);
                if (!fi.Exists) return;
                fileEncoding = TxtFileEncoding.GetEncoding(strPath, Encoding.GetEncoding("GB2312"));//取得这txt文件的编码
                read(strPath, book, fileEncoding);
            }
            catch(Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
        private void read(string strPath,int book,Encoding fileEncoding)
        {
            using (StreamReader reader = new StreamReader(strPath, fileEncoding))
            {
                reader.BaseStream.Seek(book, SeekOrigin.Begin);
                char[] buffer = new char[512];
                reader.Read(buffer, 0, buffer.Length);
                string text = new string(buffer);
                textBox1.Text = text;
            }
        }
        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Right)
            {
                book += 512;
                read(strPath, book, fileEncoding);
            }
            else if (e.Key == System.Windows.Input.Key.Left)
            {
                book -= 512;
                if (book < 0) book = 0;
                read(strPath, book, fileEncoding);
            }
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            using (System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog() { InitialDirectory = AppDomain.CurrentDomain.BaseDirectory })
            {
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    strPath = ofd.FileName;
                    fileEncoding = TxtFileEncoding.GetEncoding(strPath, Encoding.GetEncoding("GB2312"));//取得这txt文件的编码
                    book = 0;
                    read(strPath, book, fileEncoding);
                }
            }        }问题是:
1. 按下左右键之后确实可以翻页,但是新一页的前几行总是前一页已经看过的。我试着调整了一下book += 512; 有一点用处,但是换一个txt文档就又不行了。
2. 按下左右键之后,有时候新一页的第一行是乱码,后面又好了。
3. 点击按钮打开一个新文档之后可以显示第一页,但是窗体不再触发KeyDown事件,左右键翻页没用了。而我最小化窗体再还原,KeyDown事件又可以触发了。
求助高手,看看我的代码哪儿有问题。

解决方案 »

  1.   


    应该是中文的原因,你的txt里存储的是什么?byte?
      

  2.   

    觉得可以用读行来,先把内容存放到List里面
    List<string> lstr = File.ReadAllLines("要读的文件名").ToList();
    然后就可以想要那行就可以读那行
      

  3.   

    不要用Read直接用ReadLine一次读取一行,然后在textbox中显示就可以了,如果不够显示可以分几次显示
    LZ肯定是想在上班的时候偷偷看小说可以做快捷键设置字体完全透明
      

  4.   


    byte[] a= fileEncoding.GetBytes(text);
    return a.Length;
    read(strPath, book, fileEncoding);方法里返回个读取的字节数
    book += 返回的字节数;