user2029074
user2029074

Reputation: 59

Maintain format when displaying .txt file

I am new to c# and I have a question that probably has a very simple solution. I want to import a .txt file for viewing into a textbox and maintain the format of the original file (all the correct spacings). Is this possible? I am using the following code to open the .txt files when the user clicks a button and have the files displayed. Again, I am very new to programming and any help would be greatly appreciated.

OpenFileDialog ofd = new OpenFileDialog();

ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    StreamReader sr = File.OpenText(ofd.FileName);
    string s = sr.ReadLine();
    StringBuilder sb = new StringBuilder();
    while (s != null)
    {
        sb.Append(s);
        s = sr.ReadLine();
    }
    sr.Close();
    textBox1.Text = sb.ToString();
}

Upvotes: 0

Views: 968

Answers (2)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

I believe that you should use

sb.AppendLine(); 

instead of sb.Append();

now, you could (should) also use ReadToEnd() , as suggested by David Heffernan.

using(StreamReader sr = File.OpenText(ofd.FileName)) {
   textBox1.Text = sr.ReadToEnd();
}

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 612934

I believe that you are over-thinking this. There's no need for your loop and the framework already provides convenience methods that do exactly what you want.

I'd write the code like this:

using (StreamReader sr = new StreamReader(ofd.FileName))
{
    textBox1.Text = sr.ReadToEnd();
}

I guess your question about preserving the spacing was motivated by the fact that your loop doesn't preserve line breaks. That's yet another reason for using the built-in framework. Let it take the strain and get the details right.

Upvotes: 1

Related Questions