Hyluss

Serialize/Deserialize Dictionary<int, object>

Jul 18th, 2019
533
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.45 KB | None | 0 0
  1. public static void Serialize<Object>(Object dictionary, Stream stream)
  2.     {
  3.         try // try to serialize the collection to a file
  4.         {
  5.             using (stream)
  6.             {
  7.                 // create BinaryFormatter
  8.                 BinaryFormatter bin = new BinaryFormatter();
  9.                 // serialize the collection (EmployeeList1) to file (stream)
  10.                 bin.Serialize(stream, dictionary);
  11.             }
  12.         }
  13.         catch (IOException)
  14.         {
  15.         }
  16.     }
  17.  
  18.     public static Object Deserialize<Object>(Stream stream) where Object : new()
  19.     {
  20.         Object ret = CreateInstance<Object>();
  21.         try
  22.         {
  23.             using (stream)
  24.             {
  25.                 // create BinaryFormatter
  26.                 BinaryFormatter bin = new BinaryFormatter();
  27.                 // deserialize the collection (Employee) from file (stream)
  28.                 ret = (Object)bin.Deserialize(stream);
  29.             }
  30.         }
  31.         catch (IOException)
  32.         {
  33.         }
  34.         return ret;
  35.     }
  36.     // function to create instance of T
  37.     public static Object CreateInstance<Object>() where Object : new()
  38.     {
  39.         return (Object)Activator.CreateInstance(typeof(Object));
  40.     }
  41.  
  42. // Usage
  43.   Serialize(userSessionLookupTable, File.Open("data.bin", FileMode.Create));
  44.         Dictionary<int, UserSessionInfo> deserializeObject = Deserialize<Dictionary<int, UserSessionInfo>>(File.Open("data.bin", FileMode.Open));
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment