Advertisement
den3107

Serialized object saver/loader

May 5th, 2015
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.20 KB | None | 0 0
  1. public class FileManager
  2.     {
  3.         public void save<T>(T serializableObject, String path, String fileName)
  4.         {
  5.             if (serializableObject == null) { return; }
  6.  
  7.             try
  8.             {
  9.                 XmlDocument xmlDocument = new XmlDocument();
  10.                 XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
  11.                 using (MemoryStream stream = new MemoryStream())
  12.                 {
  13.                     serializer.Serialize(stream, serializableObject);
  14.                     stream.Position = 0;
  15.                     xmlDocument.Load(stream);
  16.                     xmlDocument.Save(path + fileName);
  17.                     stream.Close();
  18.                 }
  19.             }
  20.             catch (Exception ex)
  21.             {
  22.                 Console.WriteLine("Error while saving " + fileName);
  23.                 Console.WriteLine("*** ERROR MESSAGE ***");
  24.                 Console.WriteLine(ex.Message);
  25.             }
  26.         }
  27.  
  28.         public T load<T>(String path, String fileName)
  29.         {
  30.             if (string.IsNullOrEmpty(fileName)) { return default(T); }
  31.  
  32.             T objectOut = default(T);
  33.  
  34.             try
  35.             {
  36.                 string attributeXml = string.Empty;
  37.  
  38.                 XmlDocument xmlDocument = new XmlDocument();
  39.                 xmlDocument.Load(path + fileName);
  40.                 string xmlString = xmlDocument.OuterXml;
  41.  
  42.                 using (StringReader read = new StringReader(xmlString))
  43.                 {
  44.                     Type outType = typeof(T);
  45.  
  46.                     XmlSerializer serializer = new XmlSerializer(outType);
  47.                     using (XmlReader reader = new XmlTextReader(read))
  48.                     {
  49.                         objectOut = (T)serializer.Deserialize(reader);
  50.                         reader.Close();
  51.                     }
  52.  
  53.                     read.Close();
  54.                 }
  55.             }
  56.             catch (Exception ex)
  57.             {
  58.                 Console.WriteLine("Error while loading " + fileName);
  59.                 Console.WriteLine("*** ERROR MESSAGE ***");
  60.                 Console.WriteLine(ex.Message);
  61.             }
  62.  
  63.             return objectOut;
  64.         }
  65.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement