Ralph
Ralph

Reputation: 53

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?

Upvotes: 5

Views: 28817

Answers (7)

mhs
mhs

Reputation: 1042

Try changing this Line ->

txtResult.Text = line.ToString();  

to:

txtResult.Text += line.ToString();  

Upvotes: 0

arun.v1
arun.v1

Reputation: 472

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

Upvotes: 0

Likurg
Likurg

Reputation: 2760

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

Upvotes: 0

Steve
Steve

Reputation: 216343

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

Upvotes: 6

CodingBarfield
CodingBarfield

Reputation: 3398

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.

Upvotes: 0

Ctrl_Alt_Defeat
Ctrl_Alt_Defeat

Reputation: 4009

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

Upvotes: 0

sebastianmehler
sebastianmehler

Reputation: 1033

Define an List

List yourList = new List();

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

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

Upvotes: 0

Related Questions