>我试图从文本文件中加载 4 行:
email:pass
email1:pass1
email2:pass2
email3:pass3
我使用了string.split,但是当我尝试添加到我的列表中时,它加载得不好。
这是我尝试过的:
List<string> AccountList = new List<string>();
Console.Write("File Location: ");
string FileLocation = Console.ReadLine();
string[] temp = File.ReadAllLines(FileLocation);
string[] tempNew = new string[1000];
int count = 0;
foreach(var s in temp)
{
AccountList.Add(s.Split(':').ToString());
count++;
}
我检查了字符串在列表中的外观,它们是这样的:
System.String[]
我希望它是这样的:
AccountList[0] = email
AccountList[1] = pass
AccountList[2] = email1
AccountList[3] = pass1
String.Split
生成一个字符串数组
foreach(var s in temp)
{
string[] parts = s.Split(':');
string email = parts[0];
string pass = parts[1];
...
}
要存储这两条信息,请创建一个帐户类:
public class Account
{
public string EMail { get; set; }
public string Password { get; set; }
}
然后将您的帐户列表声明为List<Account>
:
var accountList = new List<Account>();
foreach(var s in File.ReadLines(FileLocation))
{
string[] parts = s.Split(':');
var account = new Account { EMail = parts[0], Password = parts[1] };
accountList.Add(account);
}
请注意,您不需要temp
变量。File.ReadLines
在循环过程中读取文件,因此不需要将整个文件存储在内存中。请参阅:File.ReadLines Method (Microsoft Docs(。
无需计数。您可以通过以下方式获得计数
int count = accountList.Count;
此列表将比与电子邮件和密码交错的列表更容易处理。
您可以按索引访问帐户
string email = accountList[i].EMail;
string pass = accountList[i].Password;
或
Account account = accountList[i];
Console.WriteLine($"Account = {account.EMail}, Pwd = {account.Password}");
从你的预期结果中你可以试试这个,string.Split
将返回一个字符串数组string[]
,尽管你的期望字符。
然后使用索引获取字符串部分。
foreach(var s in temp)
{
var arr = s.Split(':');
AccountList.Add(arr[0]);
AccountList.Add(arr[1]);
}
问题是Split
返回一个字符串数组,该数组由拆分字符之间的字符串部分组成,并且您将其视为字符串。
相反,可以通过获取File.ReadAllLines
的结果(字符串数组(并使用.SelectMany
通过拆分:
字符上的每一行来选择生成的数组(因此您为数组中的每个项目选择一个数组(,然后对结果调用ToList
(因为您将其存储在列表中(来简化代码。
例如:
Console.Write("Enter file location: ");
string fileLocation = Console.ReadLine();
// Ensure the file exists
while (!File.Exists(fileLocation))
{
Console.Write("File not found, please try again: ");
fileLocation = Console.ReadLine();
}
// Read all the lines, split on the ':' character, into a list
List<string> accountList = File.ReadAllLines(fileLocation)
.SelectMany(line => line.Split(':'))
.ToList();