读Log文件,当文件大小变化时打开文件,从新添加的几行读

来源:互联网 发布:网络空间安全期刊 编辑:程序博客网 时间:2024/06/06 09:24

全局变量

 int CurrentLine = 0;

start = new FileInfo(chewuserverlogsAppPath);
startSize = start.Length;    


1、启一个现程

  public void ListenFileChange()

        {

            int line = 0;
            this.StartLine = ReadLog(line);      //读原来文件行


            Thread thread = new Thread(new ThreadStart(FChanged));
            thread.Start();
        }


        private void FChanged()
        {
            long endSize = 0;

            while (true)
            {          
                    end = new FileInfo(AppPath);
                    endSize = end.Length;

                    if (endSize != startSize)
                    {
                        EndLine = ReadLog(CurrentLine);

                        startSize = endSize;
                    }
                }
                Thread.Sleep(1000);
            }

        }

2、读log

      public List<string> ReadLog(int currentLine)
        {
            //读取logs文件     
                    
            int current_line = 0;
            FileStream fs = new FileStream(AppPath, FileMode.OpenOrCreate, FileAccess.Read,FileShare.ReadWrite);
            StreamReader sr = new StreamReader(fs);
            string srline = sr.ReadToEnd();
            string[] arraystr = Regex.Split(srline, "\r\n");
            List<string> list = new List<string>();
            current_line = currentLine;


            while (srline != null && current_line < arraystr.Length)
            {
                list.Add(arraystr[current_line]);
                current_line++;
            }

            CurrentLine = current_line;
            fs.Close();
            sr.Close();


            return list;
        }

0 0
原创粉丝点击