当前位置: 动力学知识库 > 问答 > 编程问答 >

C# How to directly save Rich Text Box's text into rtf without Dialog Box?

问题描述:

I have a rich text box and I have also a specific button for the rich text box, which when when clicked, should save the text into rtf format at a specific location.

I Googled but didn't find the appropriate solution to achieve the file saving without using any dialog box!

I hope that I find some help here, thank you!

网友答案:

Use an OnClick event and a StreamWriter

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

The only purpose of dialog box during saving or loading files is to get heir location. If you have to use specific location - you can end up with a simple constant somewhere in your code. Just make sure that you have escaped slashes.

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

So, if you are using WinForms, then you can use RichTextBox.SaveFile:

richTextBox1.SaveFile(fileLocation );

And if you are using WPF you can use 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);
}
网友答案:

This should do the trick:

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

Make sure you use .Rtf as .Text will not include Rich Text formatted codes.

分享给朋友:
您可能感兴趣的文章:
随机阅读: