This question have been answered. I recommend sumit_programmers solution below. For now, I've removed my code, thinking it's more confusing than helpful. When I've developed it a bit further, perhaps I'll post my code here, with some comments.
You may also be interested in the answer to the question Save text from rich text box with C#. There is an answer that reminds of the accepted answer to this question. The code should work, but it's written by me, so there may be some errors or missing information.
Update: I have improved the code a bit (at least I think so). "Encoding.Default" seems to work with most common encodings, like ANSI. If the encoding is UTF-8 without byte order mark (BOM), it seems "Encoding.Default" doesn't work, though. For more information, go to informit.com/guides. Here's the code I'm using right now:
private void fileOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlgOpen = new OpenFileDialog())
{
try
{
// Available file extensions
dlgOpen.Filter = "All files(*.*)|*.*";
// Initial directory
dlgOpen.InitialDirectory = "D:";
// OpenFileDialog title
dlgOpen.Title = "Open";
// Show OpenFileDialog box
if (dlgOpen.ShowDialog() == DialogResult.OK)
{
// Create new StreamReader
StreamReader sr = new StreamReader(dlgOpen.FileName, Encoding.Default);
// Get all text from the file
string str = sr.ReadToEnd();
// Close the StreamReader
sr.Close();
// Show the text in the rich textbox rtbMain
rtbMain.Text = str;
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…