Binary deserialization: get object data - c#

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.

Related

How to save a serializable object using File.WriteAllBytes?, C#

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

how to read a binary file into a serialized list C#

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

Getting error deserializing with DataContractSerializer

When I am deserializing my object back to it's original type my object is always null.
Here is my code:
ProjectSetup obj = new ProjectSetup();
if (System.Web.HttpContext.Current.Session["ProjectSetup"] == null)
setBookProjectSetup();
string toDeserialise = System.Web.HttpContext.Current.
Session["ProjectSetup"].ToString();
DataContractSerializer dcs = new DataContractSerializer(typeof(ProjectSetup));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(toDeserialise));
obj = (ProjectSetup) dcs.ReadObject(ms, true);
return obj;
I'm going to assume that the call to setBookProjectSetup places an instance of ProjectSetup in the HttpSessionState with a key of ProjectSetup.
The issue here starts with this:
string toDeserialise = System.Web.HttpContext.Current.
Session["ProjectSetup"].ToString();
You subsequently use the contents of the toDeserialize string as the source of the deserialization.
Unless you've overloaded ToString to return a byte stream that the DataContractSerializer would be able to deserialize (it's highly unlikely) chances are you are using the implementation of ToString on Object, which will just return the type's name.
Then, you are trying to deserialize that string into your object, which isn't going to work.
What you need to do is properly serialize your object into a byte array/MemoryStream, like so:
using (var ms = new MemoryStream())
{
// Create the serializer.
var dcs = new DataContractSerializer(typeof(ProjectSetup));
// Serialize to the stream.
dcs.WriteObject(ms, System.Web.HttpContext.Current.Session["ProjectSetup"]);
At this point, the MemoryStream will be populated with a series of bytes representing your serialized object. You can then get the object back using the same MemoryStream:
// Reset the position of the stream so the read occurs in the right place.
ms.Position = 0;
// Read the object.
var obj = (ProjectSetup) dcs.ReadObject(ms);
}

c# binary serialization to file line by line or how to seperate

I have a collection of objects at runtime, which is already serializable, I need to persist the state of the object to a file. I did a quick coding using BinaryFormatter and saved A serialized object to a file.
I was thinking that I can save object per line. but when i open the file in a notepad, it was longer than a line. It wasnt scrolling. How can i store an binary serialized object per line?
I am aware that i can use a separator after each object so while reading them back to the application, i can know the end of the object. Well, according to information theory, this increases the size of the data(Sipser book).
What s the best algorithm to come up with a separator that woudldnt break the information?
Instead of binary serialization? Do you think JSon format is more feasible? can i store the entity in a json format, line by line?
Also, serialization/deserialization introduces overhead, hits the performance. Would Json be faster?
ideas?
Thanks.
Thanks.
Serialization functions like a FIFO queue, you dont have to read parts of the file because the formatter does it for you you just have to know the order you pushed objects inside.
public class Test
{
public void testSerialize()
{
TestObj obj = new TestObj();
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
formatter.Serialize(stream, 1);
formatter.Serialize(stream, DateTime.Now);
stream.Close();
}
public void TestDeserialize()
{
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.None);
IFormatter formatter = new BinaryFormatter();
TestObj obj = (TestObj)formatter.Deserialize(stream);
int obj2 = (int)formatter.Deserialize(stream);
DateTime dt = (DateTime)formatter.Deserialize(stream);
stream.Close();
}
}
[Serializable]
class TestObj
{
public string str = "1";
int i = 2;
}
Well,
Serialization/deserialization introduces overhead, would Json be faster?
JSON is still a form of serialisation, and no it probably wouldn't be faster than binary serialisation - binary serialisation is intended to be compact and quick, wheras JSON serialisation puts more emphasis on readability and so many be slower as is very likely to be less compact.
You could serialise each object individually and emit some separator between each object (e.g. a newline character), but I don't know what separator you could use that is guarenteed to not appear in the serialised data (what happens if you serialise a string containing a newline character?).
If you use a separator that the .Net serialisation framework emits then obviously you will make it difficult (if not impossible) to correctly determine where the breaks between objects are leading to deserialisation failures.
Why exactly do you want to put each object on its own line?
Binary serialization saves the data to arbitrary bytes; these bytes can include newline characters.
You're asking to use newlines as separators. Newlines are no different from other separators; they will also increase the size of the data.
You could also create a ArrayList and add the objects to it and then serialize it ;)
ArrayList list = new ArrayList();
list.Add(1);
list.Add("Hello World");
list.Add(DateTime.Now);
BinaryFormatter bf = new BinaryFormatter();
FileStream fsout = new FileStream("file.dat", FileMode.Create);
bf.Serialize(fsout, list);
fsout.Close();
FileStream fsin = new FileStream("file.dat", FileMode.Open);
ArrayList list2 = (ArrayList)bf.Deserialize(fsin);
fsin.Close();
foreach (object o in list2)
Console.WriteLine(o.GetType());

writing and reading an arraylist object to and from file

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();

Categories