0

I'm building a program for my school's swim lesson organization, and I'm saving the data using XML serialization, but I keep getting an error every time I try to deserialize the data, it says "Runtime Error: Attempting to Deserialize an Empty Stream."

Here is my code to deserialize the file and put it into a window.

    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;

        }
    }

I've tried some solutions on here, BinaryFormatter: SerializationException, but it still doesn't work. Can you guys help me?

Edit: I solved my error, using a different method, here is the code I ended up using to deserialize it. If anyone wants the serialization code, then I'll give it

    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;




    }
Community
  • 1
  • 1
Nick Wilke
  • 11
  • 1
  • 2
  • 2
    Why do you use "OpenOrCreate" flag? If the file does not exist, it should not create a spurious empty file you will stumble over next time, right? Apart from that, I think you show too little of your code for people to really being able to help. It could be none of the files exist (in that folder), it could be that the Person class definition is messed up in terms of serialization attributes. It could be, that the serialization code is buggy. None of which is visible. – BitTickler Mar 07 '15 at 00:16
  • Why are you using `BinaryFormatter` for a file with a `.xml` extension? While it's certainly possible to store binary data any file no matter what the name, using a standard extension like .xml in which one would expect to find XML data seems like it could lead to problems down the road. – dbc Mar 07 '15 at 00:32
  • 1
    The error message is likely correct. You haven't actually asked a question. What us your specific technical question? – Eric Lippert Mar 07 '15 at 00:33
  • i'm presuming if you checked for `File.exists(student.xml)` you'd find that the file doesn't exist, exactly like the message implies. – John Gardner Mar 07 '15 at 00:35

2 Answers2

1

With a FileMode of OpenOrCreate, if the file hasn't existed yet, it creates the file with no content, and thus would fail deserialization. It would be better to use:

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
}

That is probably the error you are experiencing, because you are deserializing a newly created blank file.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • The file isnt blank, its created elsewhere in the program. The file it saves to does have a string of hashed characters in it, its not empty. – Nick Wilke Mar 07 '15 at 03:55
  • I'd recommend then changing the mode to open only then, just in case. I don't see anything else wrong... Any special characters in the file that may throw it off? – Brian Mains Mar 07 '15 at 03:59
  • Some changes to other parts of the program, including changing it from OpenOrCreate to just Open worked, thanks a lot. – Nick Wilke Mar 07 '15 at 04:13
0

I strongly recommend you System.Runtime.Serialization Namespace, from System.Runtime.Serialization.dll. It provides serializers implementation such as XML and JSON.

The following example uses the 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;
    }
}

Usage example:

...
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);
...

I hope it helps.

denys-vega
  • 3,522
  • 1
  • 19
  • 24