读取文本文件错误

Reading from text file error

这是我的代码,它从一个文本文件中读取并将其放入我表单的列表框中。如果文本文件中已经有内容,它就可以工作。但是,如果我删除文本文件中的内容和 运行 程序,它会崩溃并给我错误 "Index was outside the bounds of the array."

assignment.Request.Name = columns[1];,我不确定 why/how 去修复它。

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

您需要确保列数组中至少有 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);
           }
        }

读取文件后的条件

if(columns.length >2)
{

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

}