Determine the number of lines within a text file

2019-01-02 17:16发布

Is there an easy way to programmatically determine the number of lines within a text file?

11条回答
与风俱净
2楼-- · 2019-01-02 17:28

I've tried different ways and the fastest if you have very large file is:

var counter = 0;
using (var file = new StreamReader(@"file.txt"))
{
    while (file.ReadLine() != null)
    {
        counter++;
    }
}
查看更多
看风景的人
3楼-- · 2019-01-02 17:29

This would use less memory, but probably take longer

int count = 0;
string line;
TextReader reader = new StreamReader("file.txt");
while ((line = reader.ReadLine()) != null)
{
  count++;
}
reader.Close();
查看更多
孤独总比滥情好
4楼-- · 2019-01-02 17:29

A viable option, and one that I have personally used, would be to add your own header to the first line of the file. I did this for a custom model format for my game. Basically, I have a tool that optimizes my .obj files, getting rid of the crap I don't need, converts them to a better layout, and then writes the total number of lines, faces, normals, vertices, and texture UVs on the very first line. That data is then used by various array buffers when the model is loaded.

This is also useful because you only need to loop through the file once to load it in, instead of once to count the lines, and again to read the data into your created buffers.

查看更多
人气声优
5楼-- · 2019-01-02 17:41

If by easy you mean a lines of code that are easy to decipher but per chance inefficient?

string[] lines = System.IO.File.RealAllLines($filename);
int cnt = lines.Count();

That's probably the quickest way to know how many lines.

You could also do (depending on if you are buffering it in)

#for large files
while (...reads into buffer){
string[] lines = Regex.Split(buffer,System.Enviorment.NewLine);
}

There are other numerous ways but one of the above is probably what you'll go with.

查看更多
泪湿衣
6楼-- · 2019-01-02 17:41

count the carriage returns/line feeds. I believe in unicode they are still 0x000D and 0x000A respectively. that way you can be as efficient or as inefficient as you want, and decide if you have to deal with both characters or not

查看更多
与君花间醉酒
7楼-- · 2019-01-02 17:42
try {
    string path = args[0];
    FileStream fh = new FileStream(path, FileMode.Open, FileAccess.Read);
    int i;
    string s = "";
    while ((i = fh.ReadByte()) != -1)
        s = s + (char)i;

    //its for reading number of paragraphs
    int count = 0;
    for (int j = 0; j < s.Length - 1; j++) {
            if (s.Substring(j, 1) == "\n")
                count++;
    }

    Console.WriteLine("The total searches were :" + count);

    fh.Close();

} catch(Exception ex) {
    Console.WriteLine(ex.Message);
}         
查看更多
登录 后发表回答