我正在尝试读取文本文件并将信息存储到列表中。
到目前为止,我设法从文件中读取字符串并将其拆分,但是在将信息存储到List <>时遇到了麻烦。也许我正在尝试在一个功能下做太多事情。
using System.IO;
private void openFileDialog_Click(object sender, EventArgs e)
{
if (myOpenFileDialog.ShowDialog() == DialogResult.OK) ;
using (FileStream fStream = File.OpenRead(myOpenFileDialog.FileName))
{
StreamReader reader;
reader = new StreamReader(fStream);
string line;
while ((line = reader.ReadLine()) != null)
{
string[] playerInfo = line.Split(';');
int ID = int.Parse(playerInfo[0]);
string firstName = playerInfo[1];
string lastName = playerInfo[2];
DateTime dob = DateTime.Parse(playerInfo[3]);
List<Player> players = new List<Player>
players.add(new Player(id, firstName, lastName, dob);
}
}
}
当我检查MessageBox.Show时,文件中的行数显示为0 ... 也许我的list.add代码放在错误的位置。 谢谢您的帮助和宝贵时间
答案 0 :(得分:0)
每次迭代新行时都在创建一个新列表,这可能就是为什么您没有获得正确数量的行的原因。
我还看到您的代码中存在一些sintax错误,我假设您没有直接从源代码复制/粘贴代码,这就是这些错误的原因(Add方法为大写,您在初始化列表时错过了括号)
工作代码如下:
List<Player> players = new List<Player>();
while ((line = reader.ReadLine()) != null) {
string[] playerInfo = line.Split(';');
int ID = int.Parse(playerInfo[0]);
string firstName = playerInfo[1];
string lastName = playerInfo[2];
DateTime dob = DateTime.Parse(playerInfo[3]);
players.Add(new Player(id, firstName, lastName, dob);
}
如果您想更全面地访问列表,可以通过以下方式进行操作: 假设您的班级名称为Sample:
public class Sample {
// Declare the list as a private field
private List<Player> players;
// Constructor - Creates the List instance
public Sample() {
players = new List<Player>();
}
private void openFileDialog_Click(object sender, EventArgs e) {
players.Clear(); //Clears the list
if (myOpenFileDialog.ShowDialog() == DialogResult.OK) ;
using (FileStream fStream = File.OpenRead(myOpenFileDialog.FileName)) {
StreamReader reader;
reader = new StreamReader(fStream);
string line;
while ((line = reader.ReadLine()) != null) {
string[] playerInfo = line.Split(';');
int ID = int.Parse(playerInfo[0]);
string firstName = playerInfo[1];
string lastName = playerInfo[2];
DateTime dob = DateTime.Parse(playerInfo[3]);
players.Add(new Player(id, firstName, lastName, dob);
}
}
}
}
以这种方式声明列表,您将能够从同一类内的其他方法获取列表的值。