使用C#从富文本框保存文本

时间:2010-09-20 13:31:10

标签: c# richtextbox savefiledialog

这个问题已得到解答。我对代码进行了一些改进(至少我认为是这样)。它现在提醒问题Open file in rich text box with C#的答案。如果我没有犯任何错误(我可能有),代码应该保存一个带有富文本框rtfMain文本的文件。默认文件扩展名为.txt。您也可以使用文件扩展名.rtf。

private void menuFileSave_Click(object sender, EventArgs e) 
{ 
// Create a new SaveFileDialog object 
using (SaveFileDialog dlgSave = new SaveFileDialog())
  try
  {
    // Default file extension
    dlgSave.DefaultExt = "txt"; 
    // SaveFileDialog title
    dlgSave.Title = "Save File As";
    // Available file extensions
    dlgSave.Filter = "Text Files (*.txt)|*.txt|RTF Files (*.rtf)|*.rtf"; 
    // Show SaveFileDialog box and save file
    if (dlgSave.ShowDialog() == DialogResult.OK) 
    { 
      // Save as .txt file
      if (Path.GetExtension(dlgSave.FileName) == ".txt")
      {
        rtfMain.SaveFile(dlgSave.FileName, RichTextBoxStreamType.PlainText);
      }
      // Save as .rtf file
      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)
{
}

更新:我进一步改进了代码(至少我是这么认为的)。主要区别在于您现在可以更好地控制文件编码。这是我现在正在使用的代码:

private void fileSave_Click(object sender, EventArgs e)
{
  // Text from the rich textbox rtfMain
  string str = rtfMain.Text;
  // Create a new SaveFileDialog object
  using (SaveFileDialog dlgSave = new SaveFileDialog())
  try
  {
    // Available file extensions
    dlgSave.Filter = "All Files (*.*)|*.*";
    // SaveFileDialog title
    dlgSave.Title = "Save";
    // Show SaveFileDialog
    if (dlgSave.ShowDialog() == DialogResult.OK && dlgSave.FileName.Length > 0)
    {
      // Save file as utf8 without byte order mark (BOM)
      // ref: http://msdn.microsoft.com/en-us/library/s064f8w2.aspx
      UTF8Encoding utf8 = new UTF8Encoding();
      StreamWriter sw = new StreamWriter(dlgSave.FileName, false, utf8);
      sw.Write(str);
      sw.Close();
    }
  }
  catch (Exception errorMsg)
  {
    MessageBox.Show(errorMsg.Message);
  } 
}

2 个答案:

答案 0 :(得分:4)

像这样:

 rtfMain.SaveFile(dlgSave.FileName);

答案 1 :(得分:-3)

此处的代码可以保存格式化的.doc文件。当我使用它来保存.docx文件时,它会保存它,但是当我尝试使用Microsoft Word打开保存的文件时,会显示一条错误消息。