c#读取文本文件的行数
时间: 2023-12-05 11:03:17 浏览: 159
要在C#中读取文本文件的行数,可以使用以下代码:
```csharp
using System;
using System.IO;
class Program
{
static void Main(string\[\] args)
{
string filePath = "L:\\Code\\1.txt"; // 文件路径
int lineCount = GetLineCount(filePath); // 调用方法获取行数
Console.WriteLine("该文件一共有" + lineCount + "行");
Console.ReadKey();
}
public static int GetLineCount(string filePath)
{
int lineCount = 0;
using (StreamReader sr = new StreamReader(filePath))
{
while (sr.ReadLine() != null)
{
lineCount++;
}
}
return lineCount;
}
}
```
以上代码中,`GetLineCount`方法接收一个文件路径作为参数,使用`StreamReader`读取文件的每一行,并通过计数器统计行数。最后返回行数。在`Main`方法中,我们调用`GetLineCount`方法并输出行数。请注意,你需要将文件路径`filePath`替换为你实际的文件路径。\[1\]
#### 引用[.reference_title]
- *1* [C#读取txt文本内容行数](https://blog.csdn.net/qq_22889875/article/details/77924840)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [C#语言读取txt行列数据](https://blog.csdn.net/chengoes/article/details/121409682)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [通过程序 VB.Net 或 C# 读取文本文件行数](https://blog.csdn.net/weixin_34218890/article/details/86309622)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文