user3206911
user3206911

Reputation: 117

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!

Upvotes: 1

Views: 3380

Answers (3)

JleruOHeP
JleruOHeP

Reputation: 10376

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);
}

Upvotes: 3

Dave Zych
Dave Zych

Reputation: 21887

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);
    }
}

Upvotes: 2

Hanlet Escaño
Hanlet Escaño

Reputation: 17370

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.

Upvotes: 0

Related Questions