这是我的代码,它从文本文件中读取并将其放入表单上的列表框中。如果文本文件中已有某些内容,则可以正常工作。但是,如果我删除文本文件中的内容并运行程序,它会崩溃并给出错误"索引超出了数组的范围。"
assignment.Request.Name = columns[1];
,我不知道为什么/如何修复它。
public static List<Assignment> GetAssignment()
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
StreamReader textIn =
new StreamReader(
new FileStream(path3, FileMode.OpenOrCreate, FileAccess.Read));
List<Assignment> assignments = new List<Assignment>();
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
string[] columns = row.Split('|');
Assignment assignment = new Assignment();
assignment.Employee.Name = columns[0];
assignment.Request.Name = columns[1];
assignments.Add(assignment);
}
textIn.Close();
return assignments;
}
答案 0 :(得分:1)
您需要确保列数组中至少有2个项目,否则它将尝试访问不存在的数组项目:
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
string[] columns = row.Split('|');
if(columns.length>=2)
{
Assignment assignment = new Assignment();
assignment.Employee.Name = columns[0];
assignment.Request.Name = columns[1];
assignments.Add(assignment);
}
}
答案 1 :(得分:1)
阅读文件后的PUt条件。
if(columns.length >2)
{
assignment.Employee.Name = columns[0];
assignment.Request.Name = columns[1];
assignments.Add(assignment);
}