Click here to Skip to main content
14,447,082 members
Rate this:
Please Sign up or sign in to vote.
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 22:44pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

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[^]
   
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
Member 14596277 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
Member 14596277 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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100