c#读取txt文档,生成一个list
时间: 2024-05-03 12:17:42 浏览: 19
可以使用System.IO命名空间下的StreamReader类和List泛型来实现:
```csharp
using System.IO;
using System.Collections.Generic;
// 读取txt文档并生成List
public List<string> ReadTextToList(string filePath)
{
List<string> list = new List<string>();
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
list.Add(line);
}
}
return list;
}
```
其中,filePath是txt文件的路径,返回的list即为读取的文本内容。
相关问题
c#读取txt形成一个list
你可以使用以下代码读取一个txt文件并将每行存储到一个list中:
```csharp
using System.Collections.Generic;
using System.IO;
List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
}
```
这里我们使用了一个 `StreamReader` 对象来读取文件,然后使用 `ReadLine()` 方法逐行读取文件内容,并将每行存储到 `lines` 列表中。注意,在使用完 `StreamReader` 后需要调用 `Dispose()` 方法释放资源。
C# 使用list生成一个txt文件
你可以使用C#中的`StreamWriter`类来创建和写入一个文本文件。以下是使用`List<string>`对象生成一个文本文件的示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main(string[] args)
{
// 创建一个List<string>对象
List<string> lines = new List<string>();
lines.Add("第一行文本");
lines.Add("第二行文本");
lines.Add("第三行文本");
// 创建一个新的文本文件并写入List<string>对象中的所有行
using (StreamWriter writer = new StreamWriter("example.txt"))
{
foreach (string line in lines)
{
writer.WriteLine(line);
}
}
Console.WriteLine("文本文件已生成。");
}
}
```
在上面的代码中,我们首先创建了一个`List<string>`对象并向其中添加了几行文本。然后,我们使用`StreamWriter`类创建了一个名为`example.txt`的新文本文件,并循环遍历`List<string>`对象中的每一行文本,将其写入到文件中。最后,我们关闭了`StreamWriter`对象并输出了一条完成消息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)