C# 三種序列化

世紀緣發表於2016-08-25

Binary

引用 using System.Runtime.Serialization.Formatters.Binary;
關鍵字: [Serializable] [NonSerialized] BinaryFormatter

\\User.cs

    [Serializable]
    public class User
    {
        public string UserName { get; set; }

        public string Password { get; set; }

        public int Age { get; set; }

        public string temp;
    }
\\Main.cs


            SaveFileDialog sfd = new SaveFileDialog();

            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                User user = new User() { UserName = "Test", Password = "123", Age = 15 };
                user.temp = "est";

                BinaryFormatter bf = new BinaryFormatter();

                using (FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write))
                {
                    bf.Serialize(fs, user);
                }


                using (Stream fs = new FileStream(sfd.FileName, FileMode.Open, FileAccess.Read))
                {
                    User temp = (User)bf.Deserialize(fs);

                    Console.WriteLine("Name:{0} Age:{1} Password:{2} Temp:{3}", temp.UserName, temp.Age, temp.Password,temp.temp);
                }
            }

相關文章