Чтение из BinaryWriter. Исключение NullReferenceException - C#
Формулировка задачи:
Создайте файл, содержащий записи о студентах из 3 групп (не менее 15).
name - string;
group - integer;
marks – массив чисел byte (оценки по трём дисциплинам);
возникает вопрос на этапе правильного чтения после записи ведь открываю в utf-8, но перед этим ошибка с ссылкой не указывающей на экземпляр объекта в методе заполнения
for (int i = 0; i < list.marks.Length; i++)
static void createDirectoryAndFile(out DirectoryInfo dir, string dirPath, string fileInitPath)
{
dir = new DirectoryInfo(dirPath);
if (!dir.Exists)
{
dir.Create();
//File.Create(dirPath + fileInitPath).Close();
}
if (!File.Exists(dirPath+fileInitPath))
File.Create(dirPath + fileInitPath).Close();
//writeInfo(dirPath + fileInitPath, mas);
}
struct StudentList
{
public string name;
public int group;
public byte[] marks;
public StudentList(string name, int group, byte[] marksInit)
{
this.name = name;
this.group = group;
marks = new byte[3];//количество дисциплин определяет длину
for (int i = 0; i < marks.Length; i++)
marks[i] = marksInit[i];
}
}
static void Write (StudentList list, string path)
{
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(list.name);
bw.Write(list.group);
for (int i = 0; i < list.marks.Length; i++)
bw.Write(list.marks[i]);
}
}
}
static void Filling (StudentList list)
{
Random rand = new Random(DateTime.Now.Millisecond);
list.name=Surname(12);//длина имени 12
list.group=rand.Next(3);//3 группы
for (int i = 0; i < list.marks.Length; i++)
list.marks[i]=(byte)rand.Next(1,6);//1-5 возможные оценки
}
static string Surname(int length)
{
Random rand = new Random(DateTime.Now.Millisecond);
string text = "";
while (text.Length < rand.Next(length))
{
char element = (char)rand.Next(33, 125);
if (Char.IsLetterOrDigit(element))
text += element;
}
return text;
}
static void taskVita()
{
Clear();
const string dirInitPath = @"C:\Users\Augustxeno\Desktop\code pr\технологии программирования\лабораторные\прочие каталоги\лабораторная 7", database="list.dat";
DirectoryInfo dir;
createDirectoryAndFile(out dir, dirInitPath, database);
const byte students = 14;//15 студентов
StudentList [] list=new StudentList[students];
for (byte i = 0; i <= students; i++)
{
Filling(list[i]);
Write(list[i], dirInitPath + database);
}
ReadKey();
}
с hex editor разобрался
Решение задачи: «Чтение из BinaryWriter. Исключение NullReferenceException»
textual
Листинг программы
List<Student> studentsList = new List<Student>();
using (FileStream fs = new FileStream(Path.Combine(dirInitPath, database), FileMode.Open))
using (BinaryReader br = new BinaryReader(fs))
{
while (fs.Position != fs.Length)
{
string name = br.ReadString();
int group = br.ReadInt32();
byte[] marks = br.ReadBytes(3);
studentsList.Add(new Student(name, group, marks));
}
}