Question

Hello. Recently, I learned about the class TextReader and about how to read a text file. However, there are some things I don't really understand.

Assuming this is a new object:

TextReader TR = new StreamReader(@"C:\Users\Administrator\Desktop\Text1.txt");

So I want to know how many letters are in there so I'm typing this, right?

Console.WriteLine(TR.ReadToEnd().Length);

However, it returns a number for the first line, it's current, but when I'm adding new lines. The length increases with or without anything typed. Assuming it's the \n code which is a new line [maybe I'm wrong but it's making sense]

So i need to decrease the length like that:

current length - line count*2

So I get the right amount of letters in my text file. The problem is: how do I get the number of lines?

Is there another way to check for the letter's count? If there is, how? Anyway, how do I get the number of Lines in the text file??

Thanks. =)

Was it helpful?

Solution

Since .NET framework 2.0 there is a shortcut method ReadAllLines:

var lines = System.IO.File.ReadAllLines("file.txt");
var count = lines.Length;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top