Click here to Skip to main content
15,867,834 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello :) I need to search for all C#-Keywords in a file(any file, doesn't matter), and display all occurrences in a RichTextBox.

For example: The user presses a button, and an OpenFileDialog will appear.(I already did that part) -Then, after pressing OK, with the file of their choice, it would read all lines/text in the file, and extract all occurrences of C#-Keywords, and display the extracted occurrences in a RichTextBox.

Any idea how I would do that?

-I Don't mean: "Find the first occurrence!", I mean "Find ALL Occurrences!"

Any help would be highly appreciated :)

What I have tried:

I deleted my non-working code accidentally :)
Posted
Updated 31-Oct-19 21:44pm

1 solution

Here is a simple example to get you started, it prints the line numbers and the text of the lines:
this.FindWords("test.txt", "private");

private void FindWords(string fileName, string searchString)
{
    string line;
    int count = 1;

    using (TextReader reader = File.OpenText(fileName))
    {
        while ((line = reader.ReadLine()) != null)
        {
            if (line.Contains(searchString))
            {
                Console.WriteLine(count + " " + line);
            }

            count++;
        }
    }
}

It would be a good idea to improve this with Regex search expressions, here is a nice Regex example (don't fear it aims to take away the complexity of Regex):
Converting Wildcards to Regexes[^]

Another idea would be to use the Fast Colored TextBox, as the standard RichTextBox is really a hassle to use: Fast Colored TextBox for Syntax Highlighting[^]
 
Share this answer
 
v2
Comments
GKP1992 1-Nov-19 4:53am    
I like how you gave them the solution but still left some things for them to figure out.
+5
The Magical Magikarp 1-Nov-19 18:44pm    
I liked your answer a lot, but it didn't completely answer my question. I used your solution, and it found the keyword "interface", but it printed the entire line, when it should have printed all occurrences of "interface", not just one line :)
RickZeeland 2-Nov-19 4:14am    
Bummer :)
then take a look at https://www.dotnetperls.com/indexof
The Magical Magikarp 3-Nov-19 6:27am    
Well, thanks! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900