c#读取文件,将文件内容存放到list
时间: 2023-11-27 11:52:15 浏览: 29
可以使用以下代码读取文件并将内容存放到List中:
```csharp
using System;
using System.IO;
using System.Collections.Generic;
class Program
{
static void Main()
{
string path = @"C:\example.txt";
List<string> lines = new List<string>();
try
{
using (StreamReader sr = new StreamReader(path))
{
string line;
while ((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
}
```
在上面的代码中,我们使用了`StreamReader`来读取文件,并将每一行添加到`List<string>`中。如果发生任何错误,我们会捕获并显示错误消息。最后,我们使用`foreach`循环遍历并打印出所有存储在`List`中的行。