How to count the text file which split with newline character

I have a file text which splited by newline character. the text file such this:

merah.dc
kuning.dc
hijau.dc
biru.dc
orange.dc
mahopermanent.dc

I want to count them by splitting with a newline character. so, the count of them are 6. I could only do this with looping:

int count = 0;
string path = "directory\\admin.txt";
StreamReader moco = File.OpenText(path);
string s; 
while ((s = moco.ReadLine())!= null)
{
    count++;
}

I want to count them with a simple way like the PHP syntax:

<?php
$file = file("directory\\admin.txt");
$count = count($file);
echo $count;
?>

The above syntax able to counts them without looping. Just use file() and count(). is any function in C# which equals with that function ?

Answers


You can use ReadLines without loading whole file into the memory (of course this method can be useful if your file is large)

int count = File.ReadLines(filename).Count();

Step 1 : You can use ReadAllLines() function to get all Lines from the given file path as a String Array.

Step 2: you can invoke Length property on the obtained String Array to get the Count of Total Lines

Try This:

using System.IO;

String [] allLines=File.ReadAllLines(@"directory\admin.txt");
int length=allLines.Length;

You don't need to split them by a new character, use File.ReadAllLines (which returns an array of strins, each element is a line).

int lineCount = File.ReadAllLines("test.txt").Length;

If you want to use split, then:

int lineCount = File.ReadAllText("test.txt").Split('\n').Count();

ReadAllText returns a strin with the entire content of the file.


int count = File.ReadAllLines(@"directory\\admin.txt").Length;

You can Split() the textfile

StreamReader moco = File.OpenText(path);
string s;
string splitArray[] = s.Split('\n'); //Split on newline

int length = splitArray[].Length;

Need Your Help

Reading blogger entries from .NET

c# .net blogs blogger

What is the best way to read entries programatically from Blogger using .NET/C#?

How to display value from SQL Server database in input box?

c# asp.net winforms data-binding

I would like to do something like simple data binding in Windows Forms, but in Web Forms. So I would like to get data from a column NAME from table CATS (one row) and display in on website in text ...