Advertisement
Guest User

Untitled

a guest
Dec 17th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3.  
  4. namespace UserAccountSerializer
  5. {
  6. class MainClass
  7. {
  8. public static void Main(string[] args)
  9. {
  10. Console.WriteLine("Username:");
  11. string uname = Console.ReadLine();
  12.  
  13. Console.WriteLine("Password:");
  14. string passwd = Console.ReadLine();
  15.  
  16. UserAccount ua = new UserAccount(uname, passwd);
  17.  
  18.  
  19. WriteToBinaryFile("userAcc.bin", ua, true);
  20.  
  21.  
  22. Console.WriteLine("Read from file. Press any key to continue.");
  23. Console.ReadKey();
  24.  
  25. UserAccount readAccount;
  26.  
  27. readAccount = ReadFromBinaryFile<UserAccount>("accounts.bin");
  28.  
  29. Console.WriteLine(readAccount.ToString());
  30.  
  31.  
  32. }
  33.  
  34. public static T ReadFromBinaryFile<T>(string filePath)
  35. {
  36. using (Stream stream = File.Open(filePath, FileMode.Open))
  37. {
  38. var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  39. return (T)binaryFormatter.Deserialize(stream);
  40. }
  41. }
  42.  
  43.  
  44. public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
  45. {
  46. using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
  47. {
  48. var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  49. binaryFormatter.Serialize(stream, objectToWrite);
  50. }
  51. }
  52. }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement