C#如何在没有对话框的情况下将Rich Text Box的文本直接保存到rtf?

时间:2014-01-21 23:34:00

标签: c#

我有一个富文本框,我还有一个富文本框的特定按钮,当点击时,应该将文本保存为特定位置的rtf格式。

我用谷歌搜索但没有找到合适的解决方案来实现文件保存而不使用任何对话框!

我希望我在这里找到一些帮助,谢谢!

3 个答案:

答案 0 :(得分:3)

保存或加载文件时对话框的唯一目的是获取继承人位置。如果必须使用特定位置 - 您可以在代码中的某个位置使用简单的常量。只要确保你有逃脱的斜杠。

const string fileLocation = @"C:\Folder\file.rtf";

因此,如果您使用的是WinForms,那么您可以使用RichTextBox.SaveFile

richTextBox1.SaveFile(fileLocation );

如果您使用的是WPF,则可以使用TextRange.Save

TextRange t = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd);
using (FileStream file = new FileStream(fileLocation, FileMode.Create))
{
    t.Save(file, System.Windows.DataFormats.Rtf);
}

答案 1 :(得分:2)

使用OnClick事件和StreamWriter

public void button_Click(object sender, EventArgs e)
{
    using(var sr = new StreamWriter(@"C:\MyFilePath\file.rtf"))
    {
        sr.Write(rtf.Rtf);
    }
}

答案 2 :(得分:0)

这应该可以解决问题:

System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test\\test.rtf");
file.WriteLine(this.richTextBox1.Rtf);
file.Close();

请确保使用.Rtf,因为.Text不会包含RTF格式的代码。