0

My streamReader is reading my textfile from a specific location but it only reads 9 lines instead of 10 lines , the textfile consists of 10 lines , what gone wrong here? Its omitting the first line and display only the rest of the 9 lines.

Here is my code :

 using (StreamReader reader = File.OpenText(Server.MapPath(@daoWordPuzzle.GetfileURL()))) { foreach (var line in reader.ReadLine()) { Response.Write(reader.ReadLine() + " <br />"); } } 

2 Answers 2

2
 using (StreamReader reader = File.OpenText(Server.MapPath(@daoWordPuzzle.GetfileURL()))) { //reader.ReadLine returns a string //so here you are iterating the first line of the file //this means line is a char foreach (var line in reader.ReadLine()) { Response.Write(reader.ReadLine() + " <br />"); } } 

What you should be doing is:

 using (StreamReader reader = File.OpenText(Server.MapPath(@daoWordPuzzle.GetfileURL()))) { string line; while((line = reader.ReadLine()) != null) { Response.Write(line + " <br />"); } } 
Sign up to request clarification or add additional context in comments.

Comments

2

Spender covered why your loop is not working and I suggest a cleaner method File.ReadLines. This will load the lines into memory as they are read, so it has low overhead.

Try:

string path = Server.MapPath(@daoWordPuzzle.GetfileURL()); foreach(string line in File.ReadLines(path)) { Response.Write(line + " <br />"); } 

2 Comments

You may want to explain why this works and why the OP's didn't. I like this solution better than @Spender's because it's cleaner - no messy while loops and variable assignments.
@m.t.bennett I made reference to spender's solution since I don't think it needs to be repeated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.