Click to See Complete Forum and Search --> : Small File Input Problem


Steve25
September 27th, 2009, 04:03 PM
I'm trying to make a simple program where a text file is read in and it prints the text in a textbox and the number of lines in the file. I cant get the number of lines to come up OK and get the file to display in the textbox. However I cannot get the program to do both these things in one program. Here is my code so far:

if (openFile.ShowDialog() == DialogResult.OK)
{
//Create variable for storing the number of lines
int lines = 0;
string fileName = openFile.FileName;
StreamReader objReader = new StreamReader(fileName);
//Loop until we reach the end of the file and increase the line count
while (objReader.ReadLine() != null)
{
lines++;
}
//Print the contents of the file to the textbox
txtFile.Text = objReader.ReadToEnd();
lblLines.Text = lines.ToString();
objReader.Close();
}

BigEd781
September 27th, 2009, 04:28 PM
You are using a stream, so when you call ReadLine( ) the position of the stream is being incremented. So, when you later call ReadToEnd( ) there is nothing left to read. Why not just create the string while you are looping through each line, i.e., get rid of the call to ReadToEnd( )?

eclipsed4utoo
September 28th, 2009, 07:44 AM
make sure you set the textbox for the text to be MultiLine.


OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
StringBuilder sb = new StringBuilder();
int counter = 0;

using (TextReader tr = new StreamReader(ofd.FileName))
{
while (tr.Peek() >= 0)
{
sb.AppendLine(tr.ReadLine());
counter++;
}
}

txtText.Text = sb.ToString();
txtCount.Text = counter.ToString();
}

Steve25
September 29th, 2009, 11:03 AM
Managed to get it working, thanks :)