Tuesday, October 7, 2008

Use BinaryFormatter for Save All Details of Conversion

The objective of BinaryFormatter are Serializes and Deserializes an object, or an entire graph of connected objects, in binary format.

Case: I try to save double value (after calculation) to file, but after read back that value and then compare both value, i get difference values.

Below are the part of code:

double d1 = 0.1 + 0.2 + 0.3;
 
//Write value to text file
StreamWriter writer = new StreamWriter("outTest1", false);
writer.WriteLine(d1);
writer.Close();
 
//Read value back from text file
StreamReader reader = new StreamReader("outTest1");
string str = reader.ReadLine();
reader.Close();
 
double d2 = Double.Parse(str);
 
//Compare values
if (d1 != d2)
{
    Console.WriteLine("d1 != d2");
    Console.WriteLine("Difference = " + (d1 - d2));
}
else
    Console.WriteLine("d1 == d2");
 
Console.WriteLine("d1: " + d1.ToString());
Console.WriteLine("d2: " + d2.ToString());
So, what the solution for that case? Use BinaryFormatter to solve that.

Below are the part of code:


FileStream fileStream = null;
BinaryFormatter binaryFormatter = new BinaryFormatter();
 
double d1 = 0.1 + 0.2 + 0.3;
 
//Serialize value instance to file
fileStream = new FileStream("outTest3", FileMode.Create);
binaryFormatter.Serialize(fileStream, d1);
fileStream.Close();
 
//Deserialize value instance from file
fileStream = new FileStream("outTest3", FileMode.Open);
double d2 = Convert.ToDouble(binaryFormatter.Deserialize(fileStream));
fileStream.Close();
 
//Compare values
if (d1 != d2)
{
    Console.WriteLine("d1 != d2");
    Console.WriteLine("Difference = " + (d1 - d2));
}
else
    Console.WriteLine("d1 == d2");
 
Console.WriteLine("d1: " + d1.ToString());
Console.WriteLine("d2: " + d2.ToString());

For safety code, specially when call Serialize or Deserialize, put on try catch block; and on catch block use SerializationException.

No comments:

Post a Comment