是否有一种简单的方法来编程确定文本文件中的行数?


当前回答

try {
    string path = args[0];
    FileStream fh = new FileStream(path, FileMode.Open, FileAccess.Read);
    int i;
    string s = "";
    while ((i = fh.ReadByte()) != -1)
        s = s + (char)i;

    //its for reading number of paragraphs
    int count = 0;
    for (int j = 0; j < s.Length - 1; j++) {
            if (s.Substring(j, 1) == "\n")
                count++;
    }

    Console.WriteLine("The total searches were :" + count);

    fh.Close();

} catch(Exception ex) {
    Console.WriteLine(ex.Message);
}         

其他回答

这将使用更少的内存,但可能需要更长的时间

int count = 0;
string line;
TextReader reader = new StreamReader("file.txt");
while ((line = reader.ReadLine()) != null)
{
  count++;
}
reader.Close();
try {
    string path = args[0];
    FileStream fh = new FileStream(path, FileMode.Open, FileAccess.Read);
    int i;
    string s = "";
    while ((i = fh.ReadByte()) != -1)
        s = s + (char)i;

    //its for reading number of paragraphs
    int count = 0;
    for (int j = 0; j < s.Length - 1; j++) {
            if (s.Substring(j, 1) == "\n")
                count++;
    }

    Console.WriteLine("The total searches were :" + count);

    fh.Close();

} catch(Exception ex) {
    Console.WriteLine(ex.Message);
}         

一个可行的选择,也是我个人使用过的,就是在文件的第一行添加您自己的头文件。我为自己的游戏定制模型格式。基本上,我有一个工具来优化我的.obj文件,去掉我不需要的垃圾,将它们转换为更好的布局,然后在第一行上写入行、面、法线、顶点和纹理uv的总数。当模型加载时,这些数据将被各种数组缓冲区使用。

这也很有用,因为您只需要循环文件一次来加载它,而不是一次来计算行数,然后再次将数据读入创建的缓冲区。

计算回车/换行次数。我相信在unicode中它们仍然分别是0x000D和0x000A。这样你就可以根据自己的意愿来决定是否要同时处理两个角色

如果你说的简单是指易于破译但效率很低的代码行?

string[] lines = System.IO.File.RealAllLines($filename);
int cnt = lines.Count();

这可能是知道行数的最快方法。

你还可以这样做(取决于你是否在缓冲它)

#for large files
while (...reads into buffer){
string[] lines = Regex.Split(buffer,System.Enviorment.NewLine);
}

还有许多其他的方法,但上面的一种可能是你会选择的。