这是我的工作代码,我有一个filewatcher监视我的日志文件,当文件更新(它更新很多)时,它会读取日志并将符合正则表达式的行输出到文本框。它的问题是它从头开始读取文件并再次重新打印正则行,因此我在文本框中得到重复的数据。我也不知道我是否正确设置了运行从单独线程读取的文件,因此我的程序不会冻结"在阅读大型日志文件时。
private void btnStart_Click(object sender, EventArgs e)
{
if ((Properties.Settings.Default.setting_logfile != "") && (Properties.Settings.Default.setting_logfolder != ""))
{
if (btnStart.Text == "Start Parsing")
{
// change text on button and switch status image
btnStart.Text = "Stop Parsing";
pbStatus.Image = Properties.Resources.online;
new Thread(() => Run()).Start();
}
else
{
btnStart.Text = "Start Parsing";
pbStatus.Image = Properties.Resources.offline;
fsWatcher.EnableRaisingEvents = false;
}
}
else
{
tbOutput.Text = "Please select a log file to parse.";
}
}
private void Run()
{
try
{
fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
fsWatcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void OnChanged(object source, FileSystemEventArgs e)
{
string line;
Regex pattern = new Regex(@"\[[\w :]+\]\s<SYSTEMWIDE_MESSAGE>:");
Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader streamReader = new StreamReader(stream);
while ((line = streamReader.ReadLine()) != null)
{
Match match = pattern.Match(line);
if (match.Success)
{
tbOutput.AppendText(line + "\r\n");
}
}
streamReader.Close();
stream.Close();
}
答案 0 :(得分:1)
你可以记住你在那里读到并从那里开始的最后一个位置。
Regex pattern = new Regex(@"\[[\w :]+\]\s<SYSTEMWIDE_MESSAGE>:");
long lastPosition = 0;
private void OnChanged(object source, FileSystemEventArgs e)
{
string line;
Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
stream.Seek(lastPosition, SeekOrigin.Begin);
StreamReader streamReader = new StreamReader(stream);
while ((line = streamReader.ReadLine()) != null)
{
if (pattern.Match(line).Success)
{
tbOutput.AppendText(line + Environment.NewLine);
}
}
lastPosition = stream.Position; // may need to subtract 1!!!
streamReader.Close();
stream.Close();
}