首页 > 解决方案 > 使用 FileDialog 读取文件并保存到 List<>

问题描述

我正在尝试读取文本文件并将信息存储到 List<> 中。

到目前为止,我设法从文件中读取字符串并将其拆分,但无法将信息存储到 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 代码在错误的位置。感谢您的帮助和时间

标签: c#

解决方案


每次迭代新行时,您都会创建一个新列表,这可能就是您没有获得正确数量的行的原因。

我还看到你的代码中有一些 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);
            }
        }
    }
}

以这种方式声明列表,您将能够从同一类中的其他方法获取列表的值。


推荐阅读