Basically, I have 5 textboxs where I enter information to be serialized to a text file. I wan't to display all the contents from the text file into a multiline textbox, this is where my problem occurs.
I can only read the first 'record' of the text file, nothing else gets displayed in the textbox. The only way im able to get everything is by creating an endless loop and catching a serialization exception when it gets to the end, which breaks the loop.
Basically, What is the proper way of doing this?
BinaryFormatter
read = new BinaryFormatter();FileStream file;
file = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read);
try
{
for (int i = 0; i < 2; i++){
Student student = (Student)read.Deserialize(file);txtDisplay.Text +=
" " + student.LastName.ToString() + ",";txtDisplay.Text +=
" " + student.FirstName.ToString() + ": ";txtDisplay.Text +=
" " + student.ID.ToString();txtDisplay.Text +=
" " + student.Class.ToString();txtDisplay.Text +=
" " + student.Grade.ToString() + "\r\n";i--;
}
}
catch (SerializationException){
}
This can't be the best way...
rPosted Jan 16, 2008, 11:25 PM
Ok, guess ill show a little more here.
[
Serializable ]public
class Student{
private string _firstName; private string _lastName; private string _ID; private string _class; private string _grade; public Student(string first, string last, string id, string program, string grade){
FirstName = first;
LastName = last;
ID = id;
Class = program;
Grade = grade;
}
public string FirstName{
get { return _firstName; } set { _firstName = value; }}
gonna leave out the rest of the public properties, nothing special with them.
and here is when I write to the file.
FileStream
file; BinaryFormatter formatter = new BinaryFormatter(); SaveFileDialog save = new SaveFileDialog(); DialogResult save1 = save.ShowDialog(); file = new FileStream(save.FileName, FileMode.Append, FileAccess.Write); Student student = new Student(txtFirst.Text, txtLast.Text,txtID.Text,txtClass.Text,txtGrade.Text); try { formatter.Serialize(file, student);}
catch (SerializationException){
MessageBox.Show("error");}
file.Close();
So im a little confused when you say to serialize the Student object instead of student. Serializing the Student object itself would get all the individual student properties? kind of confusing here lol, probably should have a better naming convention here. Anyways how do i go about doing that?
Scott LyslePosted Jan 16, 2008, 10:23 PM