试图反序列化一个空流?

时间:2015-03-07 00:10:33

标签: c# serialization

我正在为我学校的游泳课组织构建一个程序,我正在使用XML序列化保存数据,但每次我尝试反序列化数据时都会出现错误,它说“运行时错误:尝试到反序列化一个空流。“

这是我的代码,用于反序列化文件并将其放入窗口。

    public StudentProfile()
    {
        InitializeComponent();
        using (var file = File.Open(FindStudent.studentName + ".xml", FileMode.OpenOrCreate))
        {
                var bformatter = new BinaryFormatter();

                var mp = (Person)bformatter.Deserialize(file);

                file.Close();

                nameBox.Text += mp.studentName;
                parentBox.Text += mp.parentName;
                yearBox.Text += mp.year;
                semesterBox.Text += mp.semester;
                sessionBox.Text += mp.session;
                ageGroupBox.Text += mp.ageGroup;
                sessionTimeBox.Text += mp.sessionTime;
                levelBox.Text += mp.level;
                paymentTypeBox.Text += mp.paymentType;
                amountBox.Text += mp.amount;
                checkNumberBox.Text += mp.checkNumber;
                datePaidBox.Text += mp.datePaid;

        }
    }

我在这里尝试了一些解决方案BinaryFormatter: SerializationException,但它仍然不起作用。你能帮助我吗?

编辑:我使用不同的方法解决了我的错误,这里是我最终用于反序列化的代码。如果有人想要序列化代码,那么我会给它

    Stream file = File.Open(@"C:\Swimmers\" + FindStudent.studentName + ".xml", FileMode.Open);


                BinaryFormatter bformatter = new BinaryFormatter();

                Person mp = (Person)bformatter.Deserialize(file);

                file.Close();

                nameBox.Text += mp.studentName;
                parentBox.Text += mp.parentName;
                yearBox.Text += mp.year;
                semesterBox.Text += mp.semester;
                sessionBox.Text += mp.session;
                ageGroupBox.Text += mp.ageGroup;
                sessionTimeBox.Text += mp.sessionTime;
                levelBox.Text += mp.level;
                paymentTypeBox.Text += mp.paymentType;
                amountBox.Text += mp.amount;
                checkNumberBox.Text += mp.checkNumber;
                datePaidBox.Text += mp.datePaid;




    }

2 个答案:

答案 0 :(得分:1)

使用OpenOrCreate的FileMode,如果该文件尚不存在,则会创建没有内容的文件,因此无法反序列化。最好使用:

if (File.Exists(FindStudent.StudentName + ".xml"))
{
   //Serialization logic
}
else
{
  //default logic; create the file but don't deserialize
  //expect the UI to be loaded blank
}

这可能是您遇到的错误,因为您正在反序列化新创建的空白文件。

答案 1 :(得分:0)

我强烈建议您使用 System.Runtime.Serialization.dll System.Runtime.Serialization Namespace。它提供了序列化程序实现,例如 XML JSON

以下示例使用 DataContractSerializer

[DataContract]
public class Student
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int Age { get; set; }

    public void Save(string filePath)
    {
        using (var fs = File.Open(filePath, FileMode.Create))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof (Student));
            serializer.WriteObject(fs, this);
        }
    }

    public static Student Load(string filePath)
    {
        Student result = null; //or default result
        try
        {
            using (var fs = File.OpenRead(filePath))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof (Student));
                result = serializer.ReadObject(fs) as Student;
            }
        }
        catch (Exception)
        {
        }
        return result;
    }
}

用法示例:

...
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "student1.xml");
var student = new Student
{
    Name = "Student1",
    Age = 10
};

student.Save(filePath);

var studentFromFile = Student.Load(filePath);
...

我希望它有所帮助。