D
Durand
How can I write/read a structure into a binary file?
Thanks
Durand
Thanks
Durand
Ben Taitelbaum said:There are a few ways to do this, depending on how much control you want.
The easiest is to use the [Serializable] attribute. For example,
[Serializable]
public class Ubiquity
{
private Foo f;
public Ubiquity(Foo F)
{
this.f = f;
}
// some other stuff
}
[Serializable]
public class Foo
{
private int a;
public Foo(int A)
{
this.a = A;
}
// class stuff
}
now, when you want to read/write instances of this class:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class Testing
{
public static void Main(string[] args)
{
Ubiquity u = new Ubiquity(new Foo(100));
// write u to a binary file
// copied from
"ms-help://MS.VSCC.2003/MS.MSDNQTR.2003APR.1033/cpguide/html/cpconbasicseria
lization.htm"
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
// read the object back from the file
stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read,
FileShare.Read);
MyObject obj = (Ubiquity) formatter.Deserialize(stream);
stream.Close();
}
}
Note that this is an error situation if we don't have [Serializable]
just before class Foo, because Foo will be serialized as well.
See also: ISerializable interfae, SOAP/XML serialization
How can I write/read a structure into a binary file?
Thanks
Durand