I need to save an object, its serializable but I donot want to use XML.
Is it possible to write the raw bytes of the object and then read it off the disk to create the object again?
Thanks for the help!
Use a BinaryFormatter:
var formatter = new BinaryFormatter();
// Serialize
using (var stream = File.OpenWrite(path))
{
formatter.Serialize(stream, yourObject);
}
...
// Deserialize
using (var stream = File.OpenRead(path))
{
YourType yourObject = (YourType)formatter.Deserialize(stream);
}
Yes, it is called binary serialization. There are some good examples on the MSDN site:
http://msdn.microsoft.com/en-us/library/4abbf6k0(v=vs.100).aspx
Related
Can anyone tell me how to use Salar Bois serialization to disk?
I want to do the right thing since I'm optimizing both by size and time.
Specifically I had to serialize a List lp;
All what I find on the site is:
How to serialize an object:
var boisSerializer = new BoisSerializer();
using (var mem = new MemoryStream())
{
boisSerializer.Serialize(this, mem);
return mem.ToArray();
}
How to deserialize an object:
var boisSerializer = new BoisSerializer();
return boisSerializer.Deserialize<SampleObject>(dataStream);
Thanks
Patrick
Basically, you want to use a FileStream instead of a MemoryStream.
There's an example at the bottom of this MSDN page:
https://msdn.microsoft.com/en-us/library/system.io.filestream(v=vs.110).aspx
To use your code example however:
var boisSerializer = new BoisSerializer();
using (var fileStream = File.Create("c:\myfile.obj"))
{
boisSerializer.Serialize(this, fileStream);
}
Clearly, your return object will change, so you'll have to account for how you're using this code.
Is it possible to get data of the binary serialized object ( or list of othe same objects ) as it can be done in XML or soap. Please note, I have no idea about object structure ( private and public fields,etc)? By data of the binary serialized object I mean the values of all fields.
Lets say you have a stream.
object yourData;
var SerializeBinaryFileName = #"C:\Temp\binary.bf";
using (Stream stream = File.Open(SerializeBinaryFileName, FileMode.Open))
{
BinaryFormatter bformatter = new BinaryFormatter();
yourData = bformatter.Deserialize(stream);
stream.Close();
}
Then you have your object graph in the yourData variable.
You can read it as any other object graph can be read.
I have a list of events and I save it in a binary file using this code
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
using (BinaryWriter w = new BinaryWriter(fs))
{
foreach (MacroEvent macroEvent in events)
{
w.Write(macroEvent.TimeSinceLastEvent);
}
}
}
but I'm confused to how I read and get it back again in a list?
The following recipe is a good guide on how to implement ISerializable for an object you want to serialize and deserialize with a BinaryFormatter:
http://www.switchonthecode.com/tutorials/csharp-tutorial-serialize-objects-to-a-file
Here is the NET 4.0 documentation on BinaryFormatter:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx
and ISerializable:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx
Sequential file access File using serialization
Add
Using system.Io
Using system.Runtime.Serialzation.Formatters.Binary
Using System.Runtime.Serialization
Using Macro Events
name space created fileform : macroform
//Object For serializing RecordSerializables in binary format
Private Binary formatter = new binaryFormatter();
Private file stream output; //stream for writing to a file
Use method Deserialize to read data
Cast result of Deserialize to type serializeable to type serializeable this cast is necessary ,because Deserialize returns a refrence of type object and need to access properties that belong to class serializable. If an error during deserialization is thrown
a serialization is thrown and the file stream is closed
Private BinaryFormatter eader = new BinaryFormatter();
Private File stream input; // stream for reading from file
How do I deserialize a binary file to a string?
This is my sample code so far:
public function serialize()
{
FileStream fs = new FileStream("test.txt", FileMode.Append);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, textBox1.Text);
fs.Flush();
fs.Close();
}
public function deserialize()
{
FileStream fs = File.Open(openFileDialog1.FileName, FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
richTextBox1.Text = formatter.Deserialize(mystream) as string;
fs.Flush();
fs.Close();
}
When I start to debug the application, it only shows the first string of the stream. The rest of the stream did not show up. How should I fix this?
Just use
System.IO.File.WriteAllText(fileName, textBox1.Text);
and
textBox1.Text = System.IO.File.ReadAllText(fileName);
The right way to do this is to put all of the values that you want to serialize into a serializable structure and then serialize that structure. On the other end you deserialize that structure and then put the values where they need to go.
Note that the binary serializer produces binary, not text output. If you want human readable serialized data you can use the XmlSerializer instead.
Binary serialization serializes object graphs; it doesn't just write strings.
It wouldn't make sense to combine object graphs.
You should read and write the file directly using the File class.
this is simple I know, but i don't have internet access and this netcafes keyboard sucks, so if someone can answer this question please.
what would be the class ? just give me a kick in the right direction. there is simple arraylist object that I want to write and read to/ from file.
thanks
There's no single definitive answer to this question. It would depend on the format of the file and the objects in the list. You need a serializer. For example you could use BinaryFormatter which serializes an object instance into a binary file but your objects must be serializable. Another option is the XmlSerializer which uses XML format.
UPDATE:
Here's an example with BinaryFormatter:
class Program
{
static void Main()
{
var list = new ArrayList();
list.Add("item1");
list.Add("item2");
// Serialize the list to a file
var serializer = new BinaryFormatter();
using (var stream = File.OpenWrite("test.dat"))
{
serializer.Serialize(stream, list);
}
// Deserialize the list from a file
using (var stream = File.OpenRead("test.dat"))
{
list = (ArrayList)serializer.Deserialize(stream);
}
}
}
Since you did not mention what type of data this array contains, I would suggest writing the file in binary format.
Here is a good tutorial on how to read and write in binary format.
Basically, you need to use BinaryReader and BinaryWriter classes.
[Edited]
private static void write()
{
List<string> list = new List<string>();
list.Add("ab");
list.Add("db");
Stream stream = new FileStream("D:\\Bar.dat", FileMode.Create);
BinaryWriter binWriter = new BinaryWriter(stream);
binWriter.Write(list.Count);
foreach (string _string in list)
{
binWriter.Write(_string);
}
binWriter.Close();
stream.Close();
}
private static void read()
{
List<string> list = new List<string>();
Stream stream = new FileStream("D:\\Bar.dat", FileMode.Open);
BinaryReader binReader = new BinaryReader(stream);
int pos = 0;
int length = binReader.ReadInt32();
while (pos < length)
{
list.Add(binReader.ReadString());
pos ++;
}
binReader.Close();
stream.Close();
}
If your objects in the arraylist are serializable, you can opt for binary serialization. But this means any other application need to know the serialization and then only can use this files. You may like to clarify your intent of using the serialization. So the question remains, why do you need to do a serialization? If it is simple, for you own (this application's) use, you can think of binary serialization. Be sure, your objects are serializable. Otherwise, you need to think of XML serialization.
For Binary serialization, you can think of some code like this:
Stream stream = File.Open("C:\\mySerializedData.Net", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, myArray);
stream.Close();