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);
}
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With