Csharp/C#教程:使用C#从富文本框保存文本分享


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

这个问题已得到解答。 我已经改进了一些代码(至少我认为是这样)。 它现在提醒用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: https://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); } } 

像这样:

  rtfMain.SaveFile(dlgSave.FileName); 

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

上述就是C#学习教程:使用C#从富文本框保存文本分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

www.ctvol.com true Article Csharp/C#教程:使用C#从富文本框保存文本分享

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1011439.html

(0)
上一篇 2021年12月30日 上午6:06
下一篇 2021年12月30日 上午6:07

精彩推荐