I have trouble with saving file from Richtextbox to text file.
My richtextbox looks like this;
ABC ...
SDE ...
KLO ...
After i saved it looks like this:
ABC ... SDE ... KLO ...
But i want the same like richtextbox line after lines. What did i do wrong?
if (saveFileDialog2.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = File.CreateText(saveFileDialog2.FileName);
sw.WriteLine(richTextBox1.Text);
sw.Flush();
sw.Close();
//File.WriteAllText(saveFileDialog2.FileName, str);
}
You are probably getting this because you are trying to save
richTextBox1.Text(the whole text) in one line only using the following codeIt’s recommended to use
sw.WriteLine()on a specific line number inrichTextBox1then move to another line.Example
Another Solution
There’s already a built-in function for
RichTextBoxto save a file with a specific encoding. You may useRichTextBox.SaveFile()for this purpose.Example
Where
pathrepresentssaveFileDialog2.FileNamein your code. ForRichTextBoxStreamType, it’s best to set it asRichTextBoxStreamType.PlainTextas long as you do not use RTF such as Color/Font/Protection/Indent/etc…Then, you may read the file again using the following method
NOTICE: If the file is not in RTF and you try to read it in RTF (
RichTextBox.LoadFile(string path, RichTextBoxStreamType.RichText);)you may encounter formatting errors. In this case, you’ll need to catch the exception and read the file in a Plain or Unicode encoding.
Example
Thanks,
I hope you find this helpful 🙂