Open a .txt file into a richTextBox in C#

Chris Bacon picture Chris Bacon · Dec 1, 2010 · Viewed 27k times · Source

I want to be able to open a .txt file up into a richtextbox in c# and also into a global variable i have made called 'notes' but don't know how to do this. This is the code i have at the moment:

OpenFileDialog opentext = new OpenFileDialog();
if (opentext.ShowDialog() == DialogResult.OK)
{
    richTextBox1.Text = opentext.FileName;
    Globals.notes = opentext.FileName;
}

Only problem is it doesn't appear in neither the richtextbox nor in the global varibale, and the global allows it to be viewed in another richtextbox in another form. So please can you help, with ideally the .txt file going into both,

Thanks

Answer

BlueVoodoo picture BlueVoodoo · Dec 1, 2010

Do you mean you want to have the text displayed or the filename?

richTextBox1.Text = File.ReadAllText(opentext.FileName); 
Globals.notes = richTextBox1.Text;

You probably also want to correct this to:

if (opentext.ShowDialog() == DialogResult.OK)