C# 二进制反序列化中的NullReferenceException

C# 二进制反序列化中的NullReferenceException,c#,serialization,deserialization,C#,Serialization,Deserialization,因此,我有一个可序列化的类Student,我希望我的ReadFromFile方法对我的文件进行反序列化,这样我就可以知道我的对象中已经有多少记录,这样当我想向数组中添加新记录时,我就可以知道最后一个数组的索引是什么,然后我就可以将新记录放入索引号中。函数在第二次通过“Console.WriteLine(st2[j].FName+”+st2[j].LName);”时给了我一个错误,并告诉我 未处理NullReferenceException 它只写了我记录中的第一项,而不是剩下的 public s

因此,我有一个可序列化的类Student,我希望我的ReadFromFile方法对我的文件进行反序列化,这样我就可以知道我的对象中已经有多少记录,这样当我想向数组中添加新记录时,我就可以知道最后一个数组的索引是什么,然后我就可以将新记录放入索引号中。函数在第二次通过“
Console.WriteLine(st2[j].FName+”+st2[j].LName);
”时给了我一个错误,并告诉我

未处理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();
        }
    }

正确的循环应如下所示(假设数据已正确序列化):

但是,我认为序列化中有一个错误,因此仍然会出现null引用异常。
如果是这样,你能发布序列化数据的代码吗?

你为什么使用数组Students[]而不是像collection这样的动态集合?我从来没有使用过列表或集合,所以这是我想到的唯一方法。我会将
文件流
放在
using
block:
using中(FileStream output=new FileStream(…){…}
。即使出现异常,它也会导致清理。
while(true){}
无休止地循环,除非抛出异常(NullReferenceException,IndexOutOfRangeException)。
Formatter.Serialize(输出,st)
-从哪里来的
st
?不幸的是,这并没有解决问题。我用序列化函数编辑了这篇文章。我在序列化函数之外做了一些更改,现在我可以在数组中保存所有记录,但我仍然会收到相同的错误,因为我拥有的数组还有98个记录空间这就是问题所在吗?
foreach (var student in st2) // Replaces the while loop in the OP
{
    Console.WriteLine(student.FName + " " + student.LName);
    ++j;
}