How to read the first word in a text file and display it in a richTextBox

2548 views c#
5

I have a text document that has two alphanumeric words in it. I would like to read the text file and display only the first one in my richTextBox

This is what I have so far but does not seem to work:

RichTextBox.CheckForIllegalCrossThreadCalls = false;

        try
        {
            string filename = @"C:\Test\event.txt";
            if (File.Exists(filename))
            {
                var last = File.ReadLines(filename).Last();
                string[] words = last.Split(' ');
                Console.WriteLine(words[0]);
                richTextBox1.Text = File.ReadAllText(filename);

            }
            else
            {
                Debug.WriteLine("File does not exist.");

            }
        }
        catch (Exception f)
        {
            Console.WriteLine(f);
        }

At the moment it reads the entire text document.

Thanks

answered question

What do you mean display only the first one?

So in my text file I have " testing123 document" . I would like to display only the "testing123" in my richTextBox

2 Answers

5

If I understand correctly you can try to use FirstOrDefault get first line string, then use Split method to get the first word.

if (File.Exists(filename))
{
    var firstLine = File.ReadLines(filename).FirstOrDefault();
    richTextBox1.Text = firstLine.Split(' ')[0];
}

posted this
4

You are consoling out the answer, just set:

richTextBox1.Text = File.ReadAllText(filename).split(' ')[0]; 

There are probably more esoteric and performant ways to do this through binary or char reading; but this should solve your issue.

posted this

Have an answer?

JD

Please login first before posting an answer.