2

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. =)

Alberto Solano
  • 7,972
  • 3
  • 38
  • 61
HuMMeR-SI
  • 109
  • 1
  • 10
  • `it returns some number for the first line its current but when im adding new lines the length increases with or without me typing anything.` What does that mean exactly? – P.Brian.Mackey Aug 17 '12 at 20:35
  • it returns some numbe. for the first line its currect, but when i add new lines, the length increases with or without me typing anything. sorry english is not my main language :S anyway what im trying to say is that: if my text file has only 1 line the length property returns the currect number of letters however if it has morethen 1 lines it adds +2 to the count but there are no more letters.. – HuMMeR-SI Aug 17 '12 at 21:27

1 Answers1

6

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

var lines = System.IO.File.ReadAllLines("file.txt");
var count = lines.Length;
Michal Klouda
  • 14,263
  • 7
  • 53
  • 77