【发布时间】:2018-03-16 16:30:46
【问题描述】:
我想要实现的是我有一个“附加课程”文件,其中包含一些格式错误和重复错误。当我将该文件导入我的 Course 对象数组时,它应该会捕获这些错误。我被困在如何检查这些错误上,而且我在导入时遇到了问题。
有人可以看看这两个错误吗?
public void ImportCourses(string fileName, char Delim)
{
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream);
int index = 0;
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var array = line.Split(Delim);
Course C = new Course();
C.CourseCode = array[0];
C.Name = array[1];
C.Description = array[2];
C.NoOfEvaluations = int.Parse(array[3]);
courses[index++] = C;
//Console.WriteLine(C.GetInfo());
}
reader.Close();
stream.Close();
这些是我要检查的例外情况:
- 如果字段数不正确,则消息为“记录 {record number} 中的字段数无效”
- 如果课程集合中已使用课程代码,则消息为“记录 {record number} 中的课程代码正在使用中”
- 如果评估次数不是数字,则消息为“记录 {record number} 中的评估次数格式不正确。
我收到“索引超出范围数组”异常,我不知道从哪里开始。
这是我要导入的 .txt:
【问题讨论】:
-
你的代码做了很多假设你有正确的数据。
-
你对“课程”有什么声明?这可能会引发 IndexOutOfRangeException
-
@RaduUngureanu 我有一个名为 Courses 的类,我要导入/导出的类是 CourseManager
-
是的,放弃我的第一条评论。很可能 IndexOutOfRangeException 来自文件的第 6 行。您只有 3 个用逗号分隔的元素,而在代码中您尝试访问 4 个。
-
@RaduUngureanu 我的 txt 文件中有 4 个元素 CourseCode、CourseName、CourseDescription 和 NoOfEvaluations 你可以查看我提供的链接
标签: c# system.io.file