0

这是我的代码,它从文本文件中读取,并将其放入表单的列表框中。如果文本文件中已经存在某些内容,则它可以工作。但是,如果我删除文本文件中的内容并运行程序,它会崩溃并给我错误“索引超出数组范围”。

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;
    }
4

2 回答 2

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);
           }
        }
于 2015-11-20T03:52:10.070 回答
1

读取文件后的 PUt 条件。

if(columns.length >2)
{

 assignment.Employee.Name = columns[0];
            assignment.Request.Name = columns[1];
            assignments.Add(assignment);

}
于 2015-11-20T03:53:09.997 回答