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();
}
I believe that you should use
instead of
sb.Append();now, you could (should) also use
ReadToEnd(), as suggested by David Heffernan.