我有一个创建各种电话簿的项目。它需要读取一个文件并将名称输出到主窗体中的列表框中。当用户选择一个名称时,应打开一个新表格,其中包含名称电话号码和电子邮件地址。
当前没有语法错误,但是程序无法读取文件。它总是抛出异常。文件名在我的桌面上,并且我验证了文件名与代码匹配。对于为什么会这样的任何见解将不胜感激。
这是我的代码:
public partial class Form1 : Form
{
List<PersonEntry> nameList = new List<PersonEntry>();
public Form1()
{
InitializeComponent();
}
class PersonEntry
{
public string _name { get; set; }
public string _number { get; set; }
public string _email { get; set; }
}
private void GetNamesButton_Click(object sender, EventArgs e)
{
Readfile();
DisplayNameList();
}
private void Readfile()
{
try
{
StreamReader inputFile;
string line;
char[] deliminator = { ';' };
inputFile = File.OpenText("Personlist.txt");
while (!inputFile.EndOfStream)
{
//Use class
PersonEntry entry = new PersonEntry();
line = inputFile.ReadLine();
string[] tokens = line.Split(deliminator);
entry._name = tokens[0];
entry._number = tokens[1];
entry._email = tokens[2];
nameList.Add(entry);
}
}
catch
{
MessageBox.Show("Unable to open file");
}
}
private void DisplayNameList()
{
//Add the entry objects to the List
foreach (PersonEntry nameDisplay in nameList)
{
namesListBox.Items.Add(nameDisplay._name);
}
}
public void namesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (namesListBox.SelectedIndex != -1)
{
//Get full info for the selected item in the list
string name = nameList[namesListBox.SelectedIndex]._name;
string email = nameList[namesListBox.SelectedIndex]._email;
string phone = nameList[namesListBox.SelectedIndex]._number;
//Create second form for these details
DetailForm f2 = new DetailForm(name, email, phone);
f2.ShowDialog();
}
else
{
MessageBox.Show("Please select a Name.");
}
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
文件不在正确的文件夹中,异常显示正确的文件位置。移动它后,该应用程序将按预期工作。