c# how do I count lines in a textfile

前端 未结 7 1283
走了就别回头了
走了就别回头了 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 14:05

    The method you posted isn't particularly good. Lets break this apart:

    // new StreamReader("file.txt").ReadToEnd().Split(new char[] {'\n'}).Length
    //     becomes this:
    var file = new StreamReader("file.txt").ReadToEnd(); // big string
    var lines = file.Split(new char[] {'\n'});           // big array
    var count = lines.Count;
    

    You're actually holding this file in memory twice: once to read all the lines, once to split it into an array. The garbage collector hates that.

    If you like one liners, you can write System.IO.File.ReadAllLines(filePath).Length, but that still retrieves the entire file in an array. There's no point doing that if you aren't going to hold onto the array.

    A faster solution would be:

    int TotalLines(string filePath)
    {
        using (StreamReader r = new StreamReader(filePath))
        {
            int i = 0;
            while (r.ReadLine() != null) { i++; }
            return i;
        }
    }
    

    The code above holds (at most) one line of text in memory at any given time. Its going to be efficient as long as the lines are relatively short.

提交回复
热议问题