C#读取被占用文本文件的所有行

文件“xxx.txt”正由另一进程使用的情况下,不单要与只读方式打开txt文件,而且,需要共享锁。

还必须要选择flieShare方式为ReadWrite。因为随时有其他程序对其进行写操作。

            string path = Environment.CurrentDirectory + "\\logs\\log.txt";

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
            List lines = new List();
            string tem = "";
            while (true)
            {
                tem = sr.ReadLine();
                if (tem == null)
                    break;
                lines.Add(tem);

            }
            
            sr.Close();
            fs.Close();

如果只需要展示maxlines以后的内容


            int start = 0;
            while (start + maxLines < lines.Count)
            {
                start += maxLines;
            }


            for (int i = start; i < lines.Count; i++)
            {
                 ShowLog(lines[i], Brushes.Black);
            }

 显示日志到WPF RichTextBox控件

        double offsetDebug = 0;
        int maxLines = 10000;
        void ShowLog(string msg, Brush Color, bool Scrol = false)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate ()
            {
                //string s = string.Format("{0}:[{1}]", DateTime.Now, msg);
                Paragraph p = new Paragraph(new Run(msg));
                p.FontSize = 14;
                p.LineHeight = 3;
                p.Foreground = Color;
                rtb_Msg.Document.Blocks.Add(p);

                if (Scrol)
                    needAutoScroll(rtb_Msg, ref offsetDebug);


                if (rtb_Msg.Document.Blocks.Count > maxLines)
                    for (int i = maxLines; i < rtb_Msg.Document.Blocks.Count; i++)
                    {
                        rtb_Msg.Document.Blocks.Remove(rtb_Msg.Document.Blocks.FirstBlock);
                    }
            });
        }

 

你可能感兴趣的:(C#读取被占用文本文件的所有行)