简体   繁体   中英

Open a .txt file into a richTextBox in C#

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

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)

In c# there are not global variables. The closest thing you can get is to make the variable " public static ". But a better solution would be to make it an instance variable of an object you have access to, for example your main window class.

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName);
    richTextBox1.Text = sr.ReadToEnd();
    sr.Close();
}

Try using this, I used it for a chat program and it works fine, you can set your timer rate to whatever you want. You also don't have to use a timer, you can have a button initiate the refresh of the rich text box.

    private void refreshRate_Tick(object sender, EventArgs e)
    {
        richTextBox1.Text = File.ReadAllText(@"path.txt");
    }

Hope this helps!

FileName property of OpenFileDialog control just gives the full path of file selected by user. In order to read the content of this file, you will need to use a method like File.ReadAllText .

I hope, I am not late. It seems like there is something like:

OpenFileDialog opentext = new OpenFileDialog();
if (opentext.ShowDialog() == DialogResult.OK)
{
    string selectedFileName = opentext.FileName;
    richTextbox.LoadFile(selectedFileName, RichTextBoxStreamType.UnicodePlainText);
}

Refs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM