This question has been answered. I improved the code a bit (at least I think so). Now it resembles a reminiscent answer to the question Open a file in an extended text box with C # . If I made no mistakes (which may have), the code should save a file with text from the rtfMain rich text field. The default extension is .txt. You can also use the .rtf file extension.
private void menuFileSave_Click(object sender, EventArgs e)
{
using (SaveFileDialog dlgSave = new SaveFileDialog())
try
{
dlgSave.DefaultExt = "txt";
dlgSave.Title = "Save File As";
dlgSave.Filter = "Text Files (*.txt)|*.txt|RTF Files (*.rtf)|*.rtf";
if (dlgSave.ShowDialog() == DialogResult.OK)
{
if (Path.GetExtension(dlgSave.FileName) == ".txt")
{
rtfMain.SaveFile(dlgSave.FileName, RichTextBoxStreamType.PlainText);
}
if (Path.GetExtension(dlgSave.FileName) == ".rtf")
{
rtfMain.SaveFile(dlgSave.FileName, RichTextBoxStreamType.PlainText);
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
}
private void rtfMain_TextChanged(object sender, EventArgs e)
{
}
Update: I improved the code even further (at least I think so). The main difference is that now you have more control over the encoding of files. This is the code I'm using right now:
private void fileSave_Click(object sender, EventArgs e)
{
string str = rtfMain.Text;
using (SaveFileDialog dlgSave = new SaveFileDialog())
try
{
dlgSave.Filter = "All Files (*.*)|*.*";
dlgSave.Title = "Save";
if (dlgSave.ShowDialog() == DialogResult.OK && dlgSave.FileName.Length > 0)
{
UTF8Encoding utf8 = new UTF8Encoding();
StreamWriter sw = new StreamWriter(dlgSave.FileName, false, utf8);
sw.Write(str);
sw.Close();
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
source
share