我正在尝试将文本文件中的信息读入对象列表中,我想知道这是否是正确的方法,我真的很感激文本文件布局的任何帮助如下:
children.txt:
代码如下:
类:
class Child
{
public string name { get; set; }
public string dob { get; set; }
public string fact { get; set; }
public Child(string n, string d, string f)
{
this.name = n;
this.dob = d;
this.fact = f;
}
}
文本文件功能:
//Open file dialog (open file/read in file)
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
//created an instance of openfiledialog so we can select a file to open
OpenFileDialog od = new OpenFileDialog();
//this will invoke the dialog
od.ShowDialog();
//this will be the initial directory when we click open
od.InitialDirectory = "C:\\";
//we set the restore dir to so when we click open nxt time
//it will be the same dir we browsed last time
od.RestoreDirectory = true;
//this is to store the file name we want to open
string file = od.FileName;
//creates an instance of filestream so we can stream our file.
//here we passed the file namestored in the string file and the granted permissions
FileStream fr = new FileStream(file, FileMode.Open, FileAccess.ReadWrite);
//We created created obj of streamReader class and passed obj of fileStream
StreamReader sr = new StreamReader(fr);
//we created one more string and stored the text of our file
string line;
List<Child> childList = new List<Child>();
while ((line = sr.ReadLine()) != null)
{
string[] words = line.Split(',');
childList.Add(new Child(words[0], words[1], words[2]));
}
fr.Close();
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}