C # object serialization and deserialization

Source: Internet
Author: User

C # object serialization and deserialization, as shown in the following code example:

 
 
  1. Using System;
  2. Using System.Text;
  3. Using System.Collections.Generic;
  4. Using System.IO;
  5. Using System.Runtime.Serialization.Formatters.Binary;
  6. Class Serializableoperate
  7. {
  8. private static void Objectserializable (Object obj, String filePath)
  9. {
  10. FileStream fs = null;
  11. Try
  12. {
  13. FS = new FileStream (FilePath, FileMode.Create);
  14. BinaryFormatter bf = new BinaryFormatter ();
  15. Bf. Serialize (FS, obj);
  16. }
  17. catch (IOException ex)
  18. {
  19. Console.WriteLine ("Serialization is an error!") ");
  20. }
  21. Finally
  22. {
  23. if (fs!= null)
  24. {
  25. Fs. Close ();
  26. }
  27. }
  28. }
  29. Private static Object Objectunserializable (String filePath)
  30. {
  31. FileStream fs = null;
  32. Object obj = null;
  33. Try
  34. {
  35. FS = new FileStream (FilePath, FileMode.OpenOrCreate);
  36. BinaryFormatter bf = new BinaryFormatter ();
  37. obj = bf. Deserialize (FS);
  38. }
  39. catch (IOException ex)
  40. {
  41. Console.WriteLine ("Error during deserialization!") ");
  42. }
  43. Finally
  44. {
  45. if (fs!= null)
  46. {
  47. Fs. Close ();
  48. }
  49. }
  50. return obj;
  51. }
  52. static void Main (string[] args)
  53. {
  54. list<string> list = new list<string>{
  55. "John", "Dick", "Harry", "Zhao Liu", "Liu Bei"
  56. };
  57. String FilePath = "C:\\log.log";
  58. Console.WriteLine ("Start serialization of the collection!") Please wait a moment ... ");
  59. Serializableoperate.objectserializable (list, filePath);
  60. Console.WriteLine ("Start deserialization collection!") Please wait a moment ... ");
  61. List = (list<string>) serializableoperate.objectunserializable (FilePath);
  62. foreach (string str in list)
  63. {
  64. Console.WriteLine (str);
  65. }
  66. }
  67. }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.