Reputation: 109
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. =)
Upvotes: 2
Views: 1748
Reputation: 14521
Since .NET framework 2.0 there is a shortcut method ReadAllLines
:
var lines = System.IO.File.ReadAllLines("file.txt");
var count = lines.Length;
Upvotes: 6