How to Read/Write objects to and from a file?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm having the hardest time reading and writing a simple class object to and from a file in the CF. Could someone show me how to write a class object to a file? Then if I have multiple objects in a file, how do I read them out one by one?

Thanks
Stephen
 
The process you're describing is called serialization/deserialization. .NET
could serialize object as a binary or XML stream.
Unfortunately CF currently doesn't support that, but you can either roll out
your own custom serialization or use the XML serialization implemented in
SDF:

http://www.opennetcf.org/PermaLink.aspx?guid=3a013afd-791e-45ef-802a-4c1dbe1
cfef9

Here is the simple sample on how you could write your own serialization:

class Employee
{
string name;
string address;

public Employee(string name, string address)
{
this.name = name;
this.address = address;
}

public Employee(BinaryReader reader)
{
name = reader.ReadString();
address = reader.ReadString();
}

public string Name
{
get
{
return name;
}
}

public string Address
{
get
{
return address;
}
}

public void Save(BinaryWriter writer)
{
writer.Write(name);
writer.Write(address);
}

}


HTH... Alex

--
Alex Yakhnin .NET CF MVP
www.intelliprog.com | www.opennetcf.org

stevebju said:
I'm having the hardest time reading and writing a simple class object to
and from a file in the CF. Could someone show me how to write a class object
to a file? Then if I have multiple objects in a file, how do I read them out
one by one?
 
Hi Stephen,

Another possible solution if you want to come as close to load-in-place as
you can for managed code is to implement your class as a byte array with
properties that access the members. Then you can simple write the byte
array to the file and load it directly from the file.

For those who are not familiar with the term, load-in-place is a method of
mapping data in a file directly to data in memory. In C++ you would do this
by allocating a class instance and then loading a file directly into the
pointer to the instance (of course, a v-table can cause issues here).

--
Geoff Schwab
Program Manager
Excell Data Corporation
http://msdn.com/mobility
http://msdn.microsoft.com/mobility/prodtechinfo/devtools/netcf/FAQ/default.aspx

This posting is provided "AS IS" with no warranties, and confers no rights.
stevebju said:
I'm having the hardest time reading and writing a simple class object to
and from a file in the CF. Could someone show me how to write a class object
to a file? Then if I have multiple objects in a file, how do I read them out
one by one?
 
Back
Top