问题
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
回答1:
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)
回答2:
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.
回答3:
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.
回答4:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName);
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
}
回答5:
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!
来源:https://stackoverflow.com/questions/4326927/open-a-txt-file-into-a-richtextbox-in-c-sharp