views:

526

answers:

2

I have a RichTextBox and I want to save the text to a file. Each line of the RichTextBox are ended with CR+LF ("\n\r") but when i save it to a file, the lines only contains the LF char at the end.

If I copy the content to the clipboard instead of a file all goes right (The content of the clipboar has CR+LF at the end of each line, I can see it when I paste in Notepad++). txtClass is the RichTextBox.

private void btnToClipboard_Click(object sender, EventArgs e) { //Works as desired Clipboard.SetText(txtClass.Text); }

private void btnToFile_Click(object sender, EventArgs e)
{
    //Don't work as desired
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();             
    saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
    saveFileDialog1.FilterIndex = 2;
    saveFileDialog1.RestoreDirectory = true;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        System.IO.StreamWriter SW = new System.IO.StreamWriter(saveFileDialog1.FileName, false, Encoding.ASCII);              
        SW.Write(txtClass.Text);            
        SW.Close();
    }

}

At this moment, I also tried with

SW.NewLine = "\r\n";
SW.Newline = Environment.NewLine

and with all Enconding avalilables.

If I use SW.Write("Line One\r\nLineTwo\r\nLineThree") also works fine.

Thanks for your help

A: 

Thanks to Peter Lindholm, who gave me the correct answer in a comment.

Did you try the SaveFile method located on the RichTextBox itself? http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.savefile(VS.71).aspx

Jonathan
A: 

private void btnToFile_Click(object sender, EventArgs e) { //Don't work as desired SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (.txt)|.txt|All files (.)|."; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true;

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    System.IO.StreamWriter SW = new System.IO.StreamWriter(saveFileDialog1.FileName, false, Encoding.ASCII);              
    SW.Write(txtClass.Text);            
    SW.Close();
}

}

nilesh