开发者

Count rows in a textfile

开发者 https://www.devze.com 2023-02-14 02:40 出处:网络
I´m coding in C# and using Windows Forms. I have a textfile and want to count all开发者_如何学编程 rows that are in it.

I´m coding in C# and using Windows Forms. I have a textfile and want to count all开发者_如何学编程 rows that are in it.

Peter;25

John;31

Jane;22

Thats three lines and i want to count them for example.


The best way would be to use something like:

var count = File.ReadLines("file.txt").Count();

That will only work in .NET 4, but will read a single line at a time. If you're happy enough to load the whole file into memory in one go, you can use:

var count = File.ReadAllLines("file.txt").Length;

Note that if the file is large (or it's on a network drive etc), this could take a long time, in which case you'd want to do it off the UI thread.


If the file is not too big, you can do this:

File.ReadAllLines(filePath).Length;

(this will allocate the whole file, so make sure performance is not an issue)


        string fileName = @"X:\Testfolder\countthis.txt";
        int lineCount = 0;

        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

        StreamReader reader = new StreamReader(fs);
        Assert.Fail();

        while (reader.ReadLine() != null)
            lineCount++;
        return lineCount; 
0

精彩评论

暂无评论...
验证码 换一张
取 消