C # Visual Studio - I am trying to read a text file and display it in Richtextbox and include newlines
I am trying to read a text file and display it in Richtextbox and include new lines. Let's say I want it to read like:
Hello
Hello
Hello
But it reads like: HelloHelloHello
This is the code I have so far:
private void btnView_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.InitialDirectory = "C:\\";
op.Filter = "Txt files (*.txt)|*.txt|All Files (*.*)|*.*";
op.FilterIndex = 2;
if (op.ShowDialog() == DialogResult.OK)
{
textBox1.Text = op.FileName;
string path = op.FileName;
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while(sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
Console.WriteLine("\r\n");
}
}
richTextBox1.Text = sb.ToString();
}
}
source to share
StreamReader
separated by a symbol Environment.NewLine
. If you read the documentation , you would notice that ReadLine
these delimiters are not included. If you want to re-add them, use:
sb.Append(sr.ReadLine());
sb.Append(Environment.NewLine);
And don't call Console.WriteLine()
in WinForms application.
source to share
Another way you can do this is by using a static method of the ReadAllText()
class File
.
You just pass it the path to the text file and it will read all the text (the included lines) into a string and return it to you. Then you can simply set the result of this to your richTextBox1.Text
property for cleaner, more readable code:
if (op.ShowDialog() == DialogResult.OK)
{
textBox1.Text = op.FileName;
richTextBox1.Text = File.ReadAllText(op.FileName);
}
source to share