实时监控读取文件的代码

当实时读取一个持续写入数据的文件时,如果每次都全部读取完,随着数据量的增加,效率必然会下降,读取的目标文件每次只增加一行(或几行),而每次都需要从头读起,显示浪费资源,很不合理。我们希望只读取新增的行进行分析。网上大概有两种比较可行的办法:

(1)对于大文件,采用内存映射的办法,该办法可以参考:

http://www.cnblogs.com/criedshy/archive/2010/06/13/1757826.html

(2)读取位置定位,记住每次读取的字节位置,下一次从该字节开始读。内存映射的办法实现相对复杂,由于我所要监控的文本数据不太大,最大十几兆。因此采用第二种方法。网上找到以下方法,直接套用。

 long bytcount = 0;
        private void readData(FileSystemEventArgs e)
        {
            using (FileStream fs = new FileStream(foldPath + @"\" + file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                byte[] bytcontent = new byte[fs.Length];
                if (fs.CanRead)
                {
                    using (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));//载入文本                                                    
                            }
                            dataLengthToRead -= lengthRead;
                        }
                          sr.Close();
                    }
                    fs.Close();
                    bytcount = bytcontent.Length;//下次开始读取的起始字节数
                }
            }         

        }

  

posted @ 2017-04-14 16:40  Tracy2016  阅读(940)  评论(0)    收藏  举报