Итак, у меня есть класс Serializable Student, и я хочу, чтобы мой метод ReadFromFile десериализовал мой файл, чтобы я мог знать, сколько записей у меня уже есть в моем объекте, так что когда я хочу добавить новые записи в свой array Я могу знать, что является индексом последнего массива, и после этого я могу поместить свою новую запись в индексный номер. функция дает мне ошибку на 2-ом проходе «Console.WriteLine(st2[j].FName + " " + st2[j].LName);
» и говорит мнеNullReferenceException в двоичной десериализации
NullReferenceException был необработанное
и он просто пишет первый пункт в моем отчете, что у меня есть, а не отдых.
public static int ReadFromFile()
{
int j = 0;
string path = @"students.dat";
try
{
Students[] st2 = new Students[100];
BinaryFormatter reader = new BinaryFormatter();
FileStream input = new FileStream(path, FileMode.Open, FileAccess.Read);
st2 = (Students[])reader.Deserialize(input);
while (true)
{
st[j] = new Students();
Console.WriteLine(st2[j].FName + " " + st2[j].LName);
j++;
}
Console.WriteLine("there are " + j + "students in the file");
input.Close();
return j;
}
catch (FileNotFoundException)
{
Console.WriteLine("there are no student records yet.");
return j;
}
}
это мой метод сериализации:
public static void WriteInFileFromInput(Students[] x)
{
string path = @"students.dat";
if (File.Exists(path))
{
BinaryFormatter Formatter = new BinaryFormatter();
FileStream output = new FileStream(path, FileMode.Append, FileAccess.Write);
Formatter.Serialize(output, st);
output.Close();
}
else
{
BinaryFormatter Formatter = new BinaryFormatter();
FileStream output = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
Formatter.Serialize(output, st);
output.Close();
}
}
Есть ли причина, по которой вы используете массив Students [], а не динамическую коллекцию, такую как Collection? –
Я никогда не работал со списками или коллекциями, так что это был единственный способ, о котором я думал. – Lily
Я бы поставил этот 'FileStream' в блок' using': 'using (FileStream output = new FileStream (...)) {...}'. Это приведет к очистке, даже если есть исключение. –