序列化事例与反序列化的

序列化事例
**********
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

 [Serializable]
    public class CSaveFile      //要序列化的类 很重要的
    {
        private string DataTimer;
        private string sfile;
        public CSaveFile() { }
        public void SaveFile(string stext, string stimer)
        {
            sfile = stext;
            DataTimer = stimer;

        }
        public string InputFile()
        {
            return  sfile;
        }
        public string backfile()
        {
            return sfile;
        }

    }

序列化的
public void buttonsave()
        {
            CSaveFile sf = new CSaveFile();//序列话(1)
            string ctext = this.richTextBox1.Text;
            string ctime = DateTime.Now.ToString("yyyy-M-d");
            sf.SaveFile(ctext, ctime);


            BinaryFormatter formattable = new BinaryFormatter();//序列话(2)
            string str = "Data/" + sname + ".bin";
            Stream stream = new FileStream(str, FileMode.Create, FileAccess.Write, FileShare.None);//序列话(3)
            formattable.Serialize(stream, sf);//序列话(4)
            stream.Close();//序列话(5)
            ronosave = true;
        }

反序列化的
 private void databack(string path)
        {
           BinaryFormatter formattable = new BinaryFormatter();//反序列化用的1
            string str = "Data/" + path + ".bin";
            dateTimePicker1.CustomFormat = "'现回到:'yyyy-M-d";
            try
            {
                Stream stream = new FileStream(str, FileMode.Open, FileAccess.Read, FileShare.Read);//反序列化用的2
                CSaveFile csf = (CSaveFile)formattable.Deserialize(stream);//反序列化用的3
                this.richTextBox1.Text = csf.InputFile();
                ssavefile = csf.backfile();
                stream.Close();//反序列化用的4
                this.label3.Text = "";
            }
            catch
            {
                //this.label3.Text = "  你在" + path + "这天没有记录。";
            }
        }

posted @ 2009-06-24 09:22  Rollo Geng  阅读(106)  评论(0)    收藏  举报