4
votes

When you write this code:

    string path = @"c:\temp\MyTest.txt";
    // This text is added only once to the file.
    if (!File.Exists(path))
    {
        // Create a file to write to.
        string[] createText = { "Hello", "And", "Welcome" };
        File.WriteAllLines(path, createText);
    }

resualt

Now I want to save every line of richTextBox content to new line of .txt file like result image. I write my code as below:

private void button1_Click(object sender, EventArgs e)
{
     richTextBox1.AppendText(textBox1.Text +"\n");
     System.IO.File.WriteAllText(@"C:\Users\Mohammad_Taghi\Desktop\ab\a.txt", richTextBox1.Text + Environment.NewLine);            
}

but,the result is resulat2

2
try Environment.NewLine instead of "\n"Daniel Casserly
i edited the above code,but no desired answer.john
@DanielCasserly as its not appendAllText but instead WriteAllText Environment.NewLine wouldn't bring much as he still has to replace all \n inside with the Environment.NewLine and not just add it at the end.Thomas
@Thomas good catch - I need to spend longer reading the questions.Daniel Casserly

2 Answers

4
votes

The problem is the conversion between the text enter and the enters needed for the text files. A possibility would be the following:

private void button1_Click(object sender, EventArgs e)
{
     richTextBox1.AppendText(textBox1.Text);
     System.IO.File.WriteAllText(@"C:\Users\Mohammad_Taghi\Desktop\ab\a.txt", richTextBox1.Text.Replace("\n", Environment.NewLine));            
}

The problem is not only textbox specific but can also be operating system specific (for example if you read a file created on a linux system, ....). Some systems use just \n as new lines others \r\n. C#. Normally you have to take care of using the proper variant manually.

But c# has a nice workaround there in the form of Environment.NewLine which contains the correct variant for the current system.

4
votes

For some reason the RichTextBox control contains "\n" for newlines instead of "\r\n".

Try this:

System.IO.File.WriteAllText(
    @"C:\Users\Mohammad_Taghi\Desktop\ab\a.txt",
    richTextBox1.Text.Replace("\n", Environment.NewLine));

A better way is to use richTextBox1.Lines which is a string array that contains all the lines:

System.IO.File.WriteAllLines(
    @"C:\Users\Mohammad_Taghi\Desktop\ab\a.txt",
    richTextBox1.Lines);

For completeness, here is yet another way:

richTextBox1.SaveFile(@"C:\Users\Mohammad_Taghi\Desktop\ab\a.txt",
    RichTextBoxStreamType.PlainText); //This will remove any formatting