Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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.

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?

like image 458
Ralph Avatar asked Apr 12 '12 09:04

Ralph


1 Answers

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 using statement around your disposable Stream like this:

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 using is the better way to handle this kind of situations because it automatically handles also unexpected file exceptions taking care to correctly close your Stream

like image 95
Steve Avatar answered Sep 30 '22 00:09

Steve