Guest User

Untitled

a guest
May 28th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 KB | None | 0 0
  1. public static bool ReadFile<T>(String name, ref T toBeSet)
  2. {
  3.     FileStream xmlStream = null;
  4.  
  5.     try
  6.     {
  7.     XmlSerializer xmlSer = new XmlSerializer(typeof(T));
  8.  
  9.     xmlStream = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.None);
  10.     toBeSet = (T)xmlSer.Deserialize(xmlStream);
  11.     return true;
  12.     }
  13.     catch (Exception e)
  14.     {
  15.     Console.WriteLine(e.Message);
  16.     return false;
  17.     }
  18.     finally
  19.     {
  20.     if (xmlStream != null)
  21.         xmlStream.Close();
  22.     }
  23. }
  24.  
  25.  
  26.  
  27.  
  28.  
  29. public static bool WriteFile<T>(String name, T toWrite)
  30. {
  31.     FileStream xmlStream = null;
  32.  
  33.     try
  34.     {
  35.     XmlSerializer xmlSer = new XmlSerializer(typeof(T));
  36.  
  37.     xmlStream = new FileStream(name, FileMode.Create, FileAccess.Write, FileShare.None);
  38.     xmlSer.Serialize(xmlStream, toWrite);
  39.     return true;
  40.     }
  41.     catch (Exception e)
  42.     {
  43.     Console.WriteLine(e.Message);
  44.     return false;
  45.     }
  46.     finally
  47.     {
  48.     if (xmlStream != null)
  49.         xmlStream.Close();
  50.     }
  51. }
  52.  
  53.  
  54. Used as:
  55.  
  56. class Blah
  57. {
  58.     public String Name;
  59.     public String Value;
  60. }
  61.  
  62.  
  63. void saveBlah()
  64. {
  65.     Blah blah = new Blah();
  66.     blah.Name = "blah";
  67.     blah.Value = "1";
  68.    
  69.     if(!WriteFile<Blah>("blah.xml",blah)
  70.     {
  71.         Console.WriteLine("Failed!");
  72.     }
  73.  
  74. }
Add Comment
Please, Sign In to add comment