Cerebrus

BinarySerialization Sample

Nov 25th, 2009
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.01 KB | None | 0 0
  1. //Related to question at:
  2. //http://groups.google.com/group/dotnetdevelopment/browse_thread/thread/f85d1608839546ba
  3.  
  4. class SerializationSample
  5. {
  6.   private static MemoryStream ms = null;
  7.   private static BinaryFormatter bf = null;
  8.  
  9.   static void Main()
  10.   {
  11.     decimal[] theArray = new decimal[2];
  12.     theArray[0] = 36300288.734436237M;
  13.     theArray[1] = 34176522.502899267M;
  14.  
  15.     bf = new BinaryFormatter();
  16.     ms = new MemoryStream();
  17.    
  18.     // Convert to Byte array.
  19.     byte[] theBytes = GetBytes(theArray);
  20.    
  21.     // Convert to Decimal array.
  22.     decimal[] theDecArray = GetDecimalArray(theBytes);
  23.   }
  24.  
  25.   private static byte[] GetBytes(decimal[] theArray)
  26.   {
  27.     bf.Serialize(ms, theArray);
  28.     return ms.GetBuffer();
  29.   }
  30.  
  31.   private static decimal[] GetDecimalArray(byte[] theArray)
  32.   {
  33.     try
  34.     {
  35.       if (ms.CanSeek)
  36.         ms.Seek(0, SeekOrigin.Begin);
  37.  
  38.       return (decimal[])bf.Deserialize(ms);
  39.     }
  40.     catch (InvalidCastException)
  41.     {
  42.       // Do something.
  43.     }
  44.   }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment