Ral*_*lph 5 c# full-text-search winforms
我需要帮助我正在实习的程序.我们的想法是检查用户登录任何PC的频率.当用户登录时,该信息将记录在文本文件中,如此格式.
01-01-2011 16:47:10-002481C218B0-WS3092-Chsbe (XP-D790PRO1)
Run Code Online (Sandbox Code Playgroud)
现在我需要搜索文本文件并(例如)在文本文件中搜索用户Chsbe的所有登录日期.
我的代码到目前为止:
private void btnZoek_Click(object sender, EventArgs e)
{
int counter = 0; string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\log.txt");
while((line = file.ReadLine()) != null)
{ if ( line.Contains(txtZoek.Text) )
{
txtResult.Text = line.ToString();
}
}
file.Close();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何将包含searchterm的日志中的所有字符串返回给txtResult?
你已经做得很好了.唯一的错误是写入最后一行读入文本框覆盖前一行.
您需要using
在一次性Stream中使用StringBuilder和语句,如下所示:
private void btnZoek_Click(object sender, EventArgs e)
{
int counter = 0; string line;
StringBuilder sb = new StringBuilder();
// Read the file and display it line by line.
using(System.IO.StreamReader file = new System.IO.StreamReader("c:\\log.txt"))
{
while((line = file.ReadLine()) != null)
{
if ( line.Contains(txtZoek.Text) )
{
// This append the text and a newline into the StringBuilder buffer
sb.AppendLine(line.ToString());
}
}
}
txtResult.Text = sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)
当然,你的txtResult应该将属性MultiLine设置为true,否则你将无法看到输出.
请记住,这using
是处理此类情况的更好方法,因为它会自动处理意外关闭您的Stream的意外文件异常