c# how do I count lines in a textfile

前端 未结 7 1491
走了就别回头了
走了就别回头了 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:11

    Sure - it reads the entire stream into memory. It's terse, but I can create a file today that will fail this hard.

    Read a character at a time and increment your count on newline.

    EDIT - after some quick research If you want terse and want that shiny new generic feel, consider this:

    public class StreamEnumerator : IEnumerable
    {
        StreamReader _reader;
    
        public StreamEnumerator(Stream stm)
        {
            if (stm == null)
                throw new ArgumentNullException("stm");
            if (!stm.CanSeek)
                throw new ArgumentException("stream must be seekable", "stm");
            if (!stm.CanRead)
                throw new ArgumentException("stream must be readable", "stm");
    
            _reader = new StreamReader(stm);
        }
    
        public IEnumerator GetEnumerator()
        {
            int c = 0;
            while ((c = _reader.Read()) >= 0)
            {
                yield return (char)c;
            }
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    

    which defines a new class which allows you to enumerate over streams, then your counting code can look like this:

    StreamEnumerator chars = new StreamEnumerator(stm);
    int lines = chars.Count(c => c == '\n');
    

    which gives you a nice terse lambda expression to do (more or less) what you want.

    I still prefer the Old Skool:

        public static int CountLines(Stream stm)
        {
            StreamReader _reader = new StreamReader(stm);
            int c = 0, count = 0;
            while ((c = _reader.Read()) != -1)
            {
                if (c == '\n')
                {
                    count++;
                }
            }
            return count;
        }
    

    NB: Environment.NewLine version left as an exercise for the reader

提交回复
热议问题