如何在C#中获取文件中的行数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/713986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:12:19  来源:igfitidea点击:

How to get number of rows in file in C#?

c#file-io

提问by

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?

我需要初始化二维数组,第一列是文件中的每一行。如何获取文件中的行数?

回答by Peter Lillevold

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

您必须打开每行中的文件读取以获取计数:

var lines = File.ReadAllLines(filename);
var count = lines.Length;

回答by Chris Doggett

From MSDN:

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();

回答by JoshBerke

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.

正如 Joe 指出的那样,我遗漏了所有标准错误处理,并且没有表明您将使用相同的数组来处理其余代码。

回答by Bullines

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++;
}

回答by Adam Robinson

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 lineslist to create your array.

然后您可以使用您的lines列表来创建您的阵列。

回答by Mutant

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.

计数器会给你行数。您也可以使用循环在数组中插入行。

回答by Crash893

could you go with something more exotic like a linq statement

你能不能用一些更奇特的东西,比如 linq 语句

Count * from textfile

从文本文件中计算 *

something like that?

类似的东西?