C# 追加读取txt增量

  private void GetNewTxt(string filename)
        {
           
           // while (true)
            {
                richTextBox1.Text = "";
                FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
                byte[] bytcontent = new byte[fs.Length];
                if (fs.CanRead)
                {
                    StreamReader sr = new StreamReader(fs);
                    long dataLengthToRead = fs.Length;//获取新的文件总大小
                    if (dataLengthToRead > 0 && dataLengthToRead > bytcount)
                    {
                        fs.Seek(bytcount, SeekOrigin.Begin);
                        int lengthRead = fs.Read(bytcontent, 0, Convert.ToInt32(dataLengthToRead - bytcount));//读取的大小
                       // richTextBox1.AppendText(System.Text.Encoding.Default.GetString(bytcontent));//载入文本
                        richTextBox1.Text = System.Text.Encoding.Default.GetString(bytcontent);
                       // dataLengthToRead -= lengthRead;
                    }
                    sr.Close();
                    fs.Close();
                    DateTime dtstart = DateTime.Now; // 获取当前时间
                    DateTime dtend;
                    double diff = 0;
                    while (diff < 5)//5秒执行一次
                    {
                        dtend = DateTime.Now;
                        TimeSpan ts = dtend.Subtract(dtstart);
                        diff = (double)ts.TotalSeconds;
                        Application.DoEvents();
                    }
                }
                //    DateTime dtstart = DateTime.Now; // 获取当前时间
                //    DateTime dtend;
                //    double diff = 0;
                //    while (diff < 5)//5秒执行一次
                //    {
                //        dtend = DateTime.Now;
                //        TimeSpan ts = dtend.Subtract(dtstart);
                //        diff = (double)ts.TotalSeconds;
                //        Application.DoEvents();
                //    }
                //}
                bytcount = bytcontent.Length;//记录当次总字节数
            }
        }

你可能感兴趣的:(C# 追加读取txt增量)