C # object Persistence graphic Code

Source: Internet
Author: User
Tags object serialization
This article describes several ways to persist objects other than databases. Have a good reference value, follow the small series together to see it

Object persistence refers to the technique of saving an in-memory object to a storage device that can be permanently saved, such as a disk.

This article describes several ways to persist objects other than databases.

Specific as follows:

    1. Save As text: The Memory object is saved in a byte stream to the text.

    2. Serialize to XML: objects are stored in XML format.

    3. Serialize to JSON: Serializes the object into a JSON object and then stores it.

    4. Serialize to binary: The object is serialized into a binary byte stream saved to the file.

Knowledge points involved:

    1. Serialization and deserialization

    2. Read and Write file streams

    3. ListView displays check boxes, and arranges horizontally

As shown in the "main function is to save the information entered by the user into various formats and read from the individual documents":

Save and read the text document code as follows:

<summary>///Save As text///</summary>//<param name= "sender" ></param>//<param name= "E "></param> private void Btnsavetxt_click (object sender, EventArgs e) {dictionary<string, string> dicin   FOS = Getdictionaryinfos ();   String FilePath = "ObjPerson.txt";  Using the Using keyword will automatically release the using (FileStream fs = new FileStream (FilePath, FileMode.Create)) {using (StreamWriter SW = new StreamWriter (FS, Encoding.default)) {foreach (var keyPair in Dicinfos) {SW. WriteLine (String.     Format ("{0}={1}", Keypair.key, Keypair.value)); }}}}///<summary>//read from text////</summary>//<param name= "sender" ></param>/// Lt;param name= "E" ></param> private void Btnreadtxt_click (object sender, EventArgs e) {string filePath = "obj   Person.txt ";   dictionary<string, string> dic = new dictionary<string, string> (); Using the Using keyword automatically releases the using (FileStream fs = new FileStream (filepAth, FileMode.Open)) {using (StreamReader SW = new StreamReader (FS, Encoding.default)) {while (!SW. Endofstream) {string lineinfo = sw.      ReadLine (); Dic.     ADD (lineinfo.split (' = ') [0], lineinfo.split (' = ') [1]);   }}} This.txtName.Text = dic["Name"];   This.dtBirthday.Text = dic["Birthday"];   if (dic["Gender"] = = This.rbBoy.Text) {this.rbBoy.Checked = true;   } else {this.rbGirl.Checked = true; } string[] loves = dic["Love"].   Split (' | '); foreach (Var love in loves) {foreach (var item in this.lsvLove.Items) {ListViewItem Li = Item as Listviewite     M if (li. Text = = Love) {li.     Checked = true; }    }   }  }

Save and read the XML document code as follows:

<summary>  ///Save as XML  //</summary>//<param name= "sender" ></param>  / <param name= "E" ></param>  private void Btnsavexml_click (object sender, EventArgs e)  {   Person P = Getpersoninfos ();   String FilePath = "Objperson.xml";   using (FileStream fs = new FileStream (FilePath, FileMode.Create))   {    XmlSerializer serializer = new XmlSerializer (typeof (person));    Serializer. Serialize (FS, p);   }  }  <summary>///read from XML///</summary>//  <param name= "Sender" ></param>  //<param name= "E" ></param>  private void Btnreadxml_click (object sender, EventArgs e)  { C21/>string FilePath = "Objperson.xml";   person p;   using (FileStream fs = new FileStream (FilePath, FileMode.Open))   {    XmlSerializer serializer = new XmlSerializer (typeof (person));    Object obj= Serializer. Deserialize (FS);    p = obj as person;   }   Setpersoninfos (P);  }

Save and read the JSON document as follows:

<summary>///Save as JSON///</summary>//<param name= "sender" ></param>//<param name=   "E" ></param> private void Btnsavejson_click (object sender, EventArgs e) {person p = Getpersoninfos ();   JavaScriptSerializer Jserializer = new JavaScriptSerializer (); String Strjson = Jserializer.   Serialize (P);   String Strregex = @ "\\/date\ ((\d+) \) \\/";   MatchEvaluator evaluator = new MatchEvaluator (convertjsondatetodatestring);   Time processing requires reference to System.Text.RegularExpressions; namespace regex reg = new regex (Strregex); Strjson = Reg.   Replace (Strjson, evaluator);   String FilePath = "Objperson.json"; using (FileStream fs = new FileStream (FilePath, FileMode.Create)) {using (StreamWriter SW = new StreamWriter (FS, ENC Oding. Default)) {SW.    Write (Strjson); }}}///<summary>///read from JSON////</summary>//<param name= "sender" ></param>///< param name= "e" ></param> private void Btnreadjson_click (obJect sender, EventArgs e) {JavaScriptSerializer Jserializer = new JavaScriptSerializer ();   String FilePath = "Objperson.json";   Person p; using (FileStream fs = new FileStream (FilePath, FileMode.Open)) {using (StreamReader SW = new StreamReader (FS, encod Ing. Default) {string Strjson = sw.     ReadToEnd ();     String Strregex = @ "\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; MatchEvaluator evaluator = new MatchEvaluator (convertdatestringtojsondate);     The time is processed by the regex reg = new regex (Strregex); Strjson = Reg.     Replace (Strjson, evaluator); p = Jserializer.    Deserialize<person> (Strjson);  }} Setpersoninfos (P); }

Save and read the bin document as follows:

<summary>///  Save As binary file///</summary>//  <param name= "Sender" ></param>  //<param name= "E" ></param>  private void Btnsavebin_click (object sender, EventArgs e)  { Person   p = Getpersoninfos ();   String FilePath = "Objperson.bin";   using (FileStream fs = new FileStream (FilePath, FileMode.Create)) {    BinaryFormatter bf = new BinaryFormatter ();    Bf. Serialize (FS, p);   }  }  <summary>///Read binary files///</summary>//  <param name= "Sender" ></param>  //<param name= "E" ></param>  private void Btnreadbin_click (object sender, EventArgs e)  { C20/>string FilePath = "Objperson.bin";   person p;   using (FileStream fs = new FileStream (FilePath, FileMode.Open))   {    BinaryFormatter bf = new BinaryFormatter (); c25/>p= BF. Deserialize (fs) as person;   }   Setpersoninfos (P);  }

Note: In fact, object persistence and object serialization are two different concepts. The two are related but different.

Object persistence: Enables objects to be saved to the physical storage medium, which can be reproduced after the end of the object life cycle.

Object serialization: Converts an object or data structure into a specific format that can be transmitted over a network, or stored in memory or in a file.

The above is the C # object persistence graphics code in detail, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.