Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save richTextBox content to .txt file on c#

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

like image 901
john Avatar asked Feb 08 '23 10:02

john


2 Answers

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.

like image 60
Thomas Avatar answered Feb 10 '23 22:02

Thomas


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
like image 24
Yacoub Massad Avatar answered Feb 10 '23 23:02

Yacoub Massad