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?
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?
You would have to open the file reading in each line to get the count:
var lines = File.ReadAllLines(filename);
var count = lines.Length;
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();
You could do:
System.IO.File.ReadAllLines("path").Length
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.
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++;
}
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.
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.
could you go with something more exotic like a linq statement
Count * from textfile
something like that?