tags:

views:

2171

answers:

7

Hi,

I need to initialize 2D array and first column is every row in a file. How do I get the number of rows in a file?

A: 

You would have to open the file reading in each line to get the count:

var lines = File.ReadAllLines(filename);
var count = lines.Length;
Peter Lillevold
+2  A: 

From MSDN:

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = 
   new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   counter++;
}

file.Close();
Chris Doggett
+6  A: 

You could do:

System.IO.File.ReadAllLines("path").Length

Edit

As Joe points out, I left out all the standard error handling and didn't show you would then use this same array to process in the rest of your code.

JoshBerke
upvote for ReadAllLines, but I'd actually save the array somewhere since he's going to need it again soon and check the length of the saved array.
Joel Coehoorn
I was in the process of editing put a CYA clause that I left all that out then choose not too..guess I should have. Thanks
JoshBerke
Just be careful with file size and ReadAllLines, could hit memory problems. Not really applicable with this Q, as the whole file will be read in anyway. But something normally needed to be watched especially if you don't control the file.
Richard
+1  A: 

There may be a more efficient way for larger files, but you could start with something like:

int l_rowCount = 0;
string l_path = @"C:\Path\To\Your\File.txt";
using (StreamReader l_Sr = new StreamReader(l_path)) 
{
    while (l_Sr.ReadLine())
        l_rowCount++;
}
Bullines
+1  A: 

It would probably be more useful for you to actually open the file, read the lines into a List, then create your 2D array.

List<string> lines = new List<string>()

using(System.IO.StreamReader file = new System.IO.StreamReader(fileName))
{
    while(!file.EndOfStream) lines.Add(file.ReadLine());
}

You can then use your lines list to create your array.

Adam Robinson
+1  A: 
int counter = 0;
string line;

System.IO.StreamReader file = new System.IO.StreamReader("c:\\t1.txt");
while((line = file.ReadLine()) != null)
{
    counter++;
}
file.Close();

counter will give you number of lines. you can insert line into your array as well withthe loop.

Mutant
@Mutant: you'll get more upvotes if you put file into a using block.
John Saunders
A: 

could you go with something more exotic like a linq statement

Count * from textfile

something like that?

Crash893