C#读取文本文件streamreading
时间: 2023-07-12 14:10:15 浏览: 51
您可以使用以下代码来读取文本文件并将其存储在字符串变量中:
```csharp
using System.IO;
string path = "your_file_path.txt";
string content;
using (StreamReader reader = new StreamReader(path))
{
content = reader.ReadToEnd();
}
```
在上面的代码中,我们首先定义了文件路径变量 `path`,然后使用 `StreamReader` 类来读取文本文件。 `using` 语句用于确保在使用完 `StreamReader` 对象后将其关闭,从而释放资源。最后,我们使用 `ReadToEnd()` 方法将文件的所有内容读取到字符串变量 `content` 中。
相关问题
C#读取文本文件使用streamreading,读取txt,一行一行读取,直到最后
您可以使用以下代码来一行一行地读取文本文件并将其存储在字符串变量中,直到读取到文件的末尾为止:
```csharp
using System.IO;
string path = "your_file_path.txt";
string line;
string content = "";
using (StreamReader reader = new StreamReader(path))
{
while ((line = reader.ReadLine()) != null)
{
content += line + "\n"; // 将每行内容添加到字符串变量中
}
}
```
在上面的代码中,我们首先定义了文件路径变量 `path`,然后使用 `StreamReader` 类来读取文本文件。 `using` 语句用于确保在使用完 `StreamReader` 对象后将其关闭,从而释放资源。在 `while` 循环中,我们使用 `ReadLine()` 方法逐行读取文件内容,并将每行内容添加到字符串变量 `content` 中。当读取到文件的末尾时,`ReadLine()` 方法会返回 `null`,此时循环结束,`content` 变量中存储的就是整个文件的内容。
c#读取文本文件的行数
要在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 ]