|
-
September 27th, 2009, 04:03 PM
#1
Small File Input Problem
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:
Code:
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();
}
-
September 27th, 2009, 04:28 PM
#2
Re: Small File Input Problem
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( )?
-
September 28th, 2009, 07:44 AM
#3
Re: Small File Input Problem
make sure you set the textbox for the text to be MultiLine.
Code:
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();
}
===============================
My Blog
-
September 29th, 2009, 11:03 AM
#4
Re: Small File Input Problem
Managed to get it working, thanks
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|