将错误的 .txt 文件添加到列表中的最简单方法
Easiest way to Add lines wrong a .txt file to a list
目前我正在打开 .txt 文件两次,一次是为了获取所有行的数量,第二次是根据 .txt 文件中的行数向列表中添加一行。有 easier/better 的方法吗?
这是我的代码:
List<StreamReader> lijst = new List<StreamReader>();
StreamReader something1 = new StreamReader("C:\something123.txt");
StreamReader something2 = new StreamReader("C:\something123.txt");
lijst.Add(something1);
lijst.Add(something2);
{
int l = 0;
while (lijst[1].ReadLine() != null)
{
l++;
downloadLinks.Add(lijst[1].ReadLine());
}
for (int i = 0; i < l; i++)
{
String line = lijst[0].ReadLine();
aList.Add(line);
}
}
您可以使用此功能一次读取所有行。这样你就不需要遍历一个循环,结果将在一个数组中,可以在一次调用中添加到你想要的任何列表。
var lines = File.ReadAllLines(filepath);
downloadLinks.AddRange(line);
https://msdn.microsoft.com/en-us/library/system.io.file.readalllines(v=vs.110).aspx
I want to put all the lines of the file in a list
那你现在工作太辛苦了。您可以使用 File.ReadLines
,它会产生一个 IEnumerable<string>
并将其传递到 List<string>
:
var allTextLines = new List<string>(File.ReadLines(path));
目前我正在打开 .txt 文件两次,一次是为了获取所有行的数量,第二次是根据 .txt 文件中的行数向列表中添加一行。有 easier/better 的方法吗?
这是我的代码:
List<StreamReader> lijst = new List<StreamReader>();
StreamReader something1 = new StreamReader("C:\something123.txt");
StreamReader something2 = new StreamReader("C:\something123.txt");
lijst.Add(something1);
lijst.Add(something2);
{
int l = 0;
while (lijst[1].ReadLine() != null)
{
l++;
downloadLinks.Add(lijst[1].ReadLine());
}
for (int i = 0; i < l; i++)
{
String line = lijst[0].ReadLine();
aList.Add(line);
}
}
您可以使用此功能一次读取所有行。这样你就不需要遍历一个循环,结果将在一个数组中,可以在一次调用中添加到你想要的任何列表。
var lines = File.ReadAllLines(filepath);
downloadLinks.AddRange(line);
https://msdn.microsoft.com/en-us/library/system.io.file.readalllines(v=vs.110).aspx
I want to put all the lines of the file in a list
那你现在工作太辛苦了。您可以使用 File.ReadLines
,它会产生一个 IEnumerable<string>
并将其传递到 List<string>
:
var allTextLines = new List<string>(File.ReadLines(path));