2012-04-12 2 views
5

Ho bisogno di aiuto con un programma che sto costruendo al mio internato. L'idea è di verificare la frequenza con cui un utente accede a qualsiasi PC. Quando un utente esegue il login, tali informazioni vengono registrate in un file di testo, come questo formato.C# cerca file di testo, restituisce tutte le righe contenenti una parola

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

ora ho bisogno di cercare il file di testo e (per esempio) cercare il file di testo per tutte le date di accesso per l'utente Chsbe.

Il mio codice finora:

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

La mia domanda è: come faccio a restituire tutte le stringhe nel registro che contiene il termine di ricerca a txtResult?

+1

sguardo regex –

+0

E 'possbile ottenere i sorgenti in formato XML? Altrimenti come accennato prima guardiamo le espressioni regolari. Se le ricerche diventano più complesse dai un'occhiata a qualche tipo di componenti di ricerca a testo completo –

risposta

6

si sta già facendo un buon lavoro. L'unico errore è nella scrittura dell'ultima riga letta nella casella di testo che sovrascrive quella precedente.
È necessario utilizzare uno StringBuilder e una dichiarazione using intorno al vostro flusso usa e getta in questo modo:

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

naturalmente, il vostro txtResult dovrebbe avere il MultiLine proprietà impostata su true, in caso contrario non sarà possibile vedere l'output.
Tenete a mente che using è il modo migliore per gestire questo tipo di situazioni perché gestisce automaticamente anche eccezioni di file inaspettate avendo cura di chiudere correttamente il flusso

+0

Sì! questo è! Grazie per l'aiuto veloce, Steve. – Ralph

0

Usa RichTextBox o utilizzare la proprietà multilinea ad esempio

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

Intendi Richtextbox? – basti

+0

Oh, sì, signorina, clicca – Likurg

+0

Btw. Non penso che questo sarà di grande aiuto per il battistrada. Dovresti almeno chiamare il nome della classe. Collegarsi al MSDN o mostrare l'initalizzazione .. ... che spiegherebbe di più e che ci sarebbe anche il "perché" utilizzare un richtextbox. – basti

0

Definire un elenco

Lista yourList = new List();

Sostituire la riga txtResult.Text = line.ToString();
di yourList.Add (riga);

nella lista "yourList" Hai tutte le linee che contengono l'utente

+0

Ho provato questo ma non farà un elenco a tutti .. puoi chiarire questo? – Ralph

+0

Come è il tuo codice? – sebastianmehler

0

qualcosa di simile al di sotto potrebbe aiutarti ad iniziare con 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); 
} 
0
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(); 
} 
0

Forse qualcosa di simile potrebbe funzionare.

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

Questa sarebbe la mia versione:

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

Se la lista è davvero lunga vorrei utilizzare uno StringBuilder per creare una stringa risultato sotto forma di aumento di velocità delle prestazioni.

0

provare a cambiare questa linea ->

txtResult.Text = line.ToString(); 

a:

txtResult.Text += line.ToString();