C#搜索文本文件,返回所有包含一个单词的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10120693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:30:06  来源:igfitidea点击:

C# search text file, return all lines containing a word

c#winformsfull-text-search

提问by Ralph

I need help with a program i'm building at my internship. The idea is to check how frequent a user logs in on any PC. When a user logs in, that information is logged in a text file, like this format.

我需要帮助我在实习期间建立一个程序。这个想法是检查用户登录任何 PC 的频率。当用户登录时,该信息会记录在文本文件中,就像这种格式。

01-01-2011 16:47:10-002481C218B0-WS3092-Chsbe (XP-D790PRO1)

Now i need to search the text file and (for example) search the text file for all login dates for the user Chsbe.

现在我需要搜索文本文件并(例如)搜索用户 Chsbe 的所有登录日期的文本文件。

My code so far:

到目前为止我的代码:

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(); 
        } 

My question is, How do i return all the strings in the log containing the searchterm to txtResult?

我的问题是,如何将包含搜索词的日志中的所有字符串返回到 txtResult?

采纳答案by Steve

You are already doing a good work. The only error is in the writing of the last line read into the textbox overwriting the previous one.
You need to use a StringBuilder and a usingstatement around your disposable Stream like this:

你已经做得很好了。唯一的错误是在写入最后一行读入文本框时覆盖了前一行。
您需要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();
}  

of course, your txtResult should have the property MultiLine set to true, otherwise you will be unable to see the output.
Keep in mind that usingis the better way to handle this kind of situations because it automatically handles also unexpected file exceptions taking care to correctly close your Stream

当然,您的 txtResult 应该将 MultiLine 属性设置为 true,否则您将无法看到输出。
请记住,这using是处理此类情况的更好方法,因为它还会自动处理意外的文件异常,同时注意正确关闭您的 Stream

回答by Likurg

Use richtextbox or use multiline property for example

例如使用富文本框或使用多行属性

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) )     
        {
            richtextbox1.Text += "\n" + line.ToString();
            txtresult.Text += "\n" + line.ToString();
        }     

        }  
        file.Close(); 
    } 

回答by sebastianmehler

Define an List

定义列表

List yourList = new List();

List yourList = new List();

Replace the Line txtResult.Text = line.ToString();
by yourList.Add(line);

替换行 txtResult.Text = line.ToString();
通过 yourList.Add(line);

in the List "yourList" you got all Lines containing the User

在列表“yourList”中,您获得了包含用户的所有行

回答by Ctrl_Alt_Defeat

Something like the below might help get you started with regex:

类似下面的内容可能会帮助您开始使用正则表达式:

string pattern = "Chsbe"; 
Regex rx = new Regex(pattern, RegexOptions.IgnoreCase); 
MatchCollection mc = rx.Matches(inputText); 

foreach (Match m in mc) 
{ 
    Console.WriteLine(m.Value); 
} 

回答by arun.v1

private void btnZoek_Click(object sender, EventArgs e)
{
    int counter = 0; string line;  
    StringBuilder str = new StringBuilder();
    // 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))     
        {
            str.Append(line.ToString());                
        }     
    }  
    file.Close(); 
} 

回答by CodingBarfield

Maybe something like this would work.

也许这样的事情会奏效。

    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 = txtResult.Text + Environment.Newline + line.ToString();                
        }     

        }  
        file.Close(); 
    } 

This would be my version:

这将是我的版本:

    private void btnZoek_Click(object sender, EventArgs e)
    {
        try
        {
            int counter = 0;
            string line;
            List<String> LinesFound = new List<string>();

            // 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))
                {
                    LinesFound.Add(line);
                }

            }
            file.Close();

            foreach (string Line in LinesFound)
            {
                txtResult.Text = txtResult.Text + Line + Environment.NewLine;
            }
        }
        catch (Exception)
        {
            MessageBox.Show("Error in btnZoek_Click");
        }
    }

If the list is really long I would use a StringBuilder to create a result string as a performance speedup.

如果列表真的很长,我会使用 StringBuilder 创建一个结果字符串作为性能加速。

回答by mhs

Try changing this Line ->

尝试更改此行 - >

txtResult.Text = line.ToString();  

to:

到:

txtResult.Text += line.ToString();