I'm learning C# by writing a home library manager.
I have a BookController that will store the books in a data structure and perform operations on them.
Does C# have a way of saving the data in the dictionary to a local file perhaps in an XML fashion to load later, or am I going to have to write it myself?
What is the best method of saving and loading this data available to C#? Just need pointed in a good direction.
Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.) If necessary, padding is added between struct members, to ensure that the latter one uses the correct alignment. Each primitive type T requires an alignment of sizeof(T) bytes.
Structs are stored as a concatenation of the variables they are declared to contain. The variables are stored in the order they are declared. The address of the beginning of the struct is the address of the beginning of the first variable it contains.
Actually, C# (the language) doesn't know anything about serialization, but .NET (the framework) provides lots of ways... XmlSerializer
, BinaryFormatter
, DataContractSerializer
(.NET 3.0) - or there are a few bespoke serialization frameworks too.
Which to use depends on your requirements; BinaryFormatter
is simple to use, but burns assembly metadata information into the file - making it non-portable (you couldn't open it in Java, for example). XmlSerializer
and DataContractSerializer
are primarily xml-based, making it quite portable, but fairly large unless you compress it.
Some proprietary serializers are half-way between the two; protobuf-net is a binary formatter (so very dense data), but which follows a portable standard for the data format (Google's protocol buffers spec). Whether this is useful depends on your scenario.
Typical code (here using XmlSerializer
):
XmlSerializer ser = new XmlSerializer(typeof(Foo));
// write
using (var stream = File.Create("foo.xml"))
{
ser.Serialize(stream, foo); // your instance
}
// read
using (var stream = File.OpenRead("foo.xml"))
{
Foo newFoo = (Foo)ser.Deserialize(stream);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With