Note that there are some explanatory texts on larger screens.

plurals
  1. POSave text from rich text box with C#
    primarykey
    data
    text
    <p>This question has been answered. I've improved the code a bit (at least I think so). It now reminds of the aceepted answer to the question <a href="https://stackoverflow.com/questions/3743438/open-file-in-rich-text-box-with-c">Open file in rich text box with C#</a>. If I haven't made any mistakes (which I may have), the code should save a file with text from the rich text box rtfMain. The default file extension is .txt. You can also use the file extension .rtf.</p> <pre><code>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) { } </code></pre> <hr> <p>Update: I have improved the code even further (at least I think so). The main difference is that you now have more control over the file encoding. This is the code I'm using right now:</p> <pre><code>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 &amp;&amp; dlgSave.FileName.Length &gt; 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); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload