So I have a Serializable class Student, and I want my ReadFromFile method to deserialize my file so I can know how many records I already have in my object, so that when I want to add new records to my array I can know what's the index of the last array and I can put my new record in the index number after that. the function gives me an error on the 2nd pass of "Console.WriteLine(st2[j].FName + " " + st2[j].LName);
" and tells me
NullReferenceException was unhandled
and it just writes the first item in my record that I have, not the rest.
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;
}
}
this is my Serialization method:
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();
}
}