c# how do I count lines in a textfile

前端 未结 7 1289
走了就别回头了
走了就别回头了 2021-02-04 13:39

any problems with doing this?

int  i = new StreamReader(\"file.txt\").ReadToEnd().Split(new char[] {\'\\n\'}).Length
7条回答
  •  孤街浪徒
    2021-02-04 13:57

    If you're looking for a short solution, I can give you a one-liner that at least saves you from having to split the result:

    int i = File.ReadAllLines("file.txt").Count;
    

    But that has the same problems of reading a large file into memory as your original. You should really use a streamreader and count the line breaks as you read them until you reach the end of the file.

提交回复
热议问题