c#序列化與反列化

<?xml version="1.0"?>
<Gather_Article xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Title>xxxxx </Title>
  <UrlSource>http://www.shenhua.com/html/yaowenkuaixun/yaowenkuaixun/20080423/5378.html</UrlSource>
  <Resource>国华投资公司 </Resource>
  <Content>
    
     </Content>
  <IsSave>0</IsSave>
  <Picture>
    <string>http://www.shenhua.com/upimg/userup/0804/231020432o6.jpg</string>
  </Picture>
  <Author>李少宝 </Author>
  <Date>2008-04-23</Date>
</Gather_Article> 
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Web;
using amao.Config;
using System.Web.Caching;
namespace Entity
{
    /// <summary>
    /// 实体类Gather_Article 。(属性说明自动提取数据库字段的描述信息)
    /// </summary>
    /// 
    [Serializable()]
    public class Gather_Article
    {
        public Gather_Article()
        {
        }
        #region Model
        /// <summary>
        /// 文章标题
        /// </summary>
        public string Title
        {
            set;
            get;
        }
        public string UrlSource
        {
            get;
            set;
        }
        /// <summary>
        /// 文章说明、来源
        /// </summary>
        public string Resource
        {
            set;
            get;
        }
        /// <summary>
        /// 文章正文
        /// </summary>
        public string Content
        {
            set;
            get;
        }
        /// <summary>
        /// 是否保存
        /// </summary>
        public int IsSave
        {
            set;
            get;
        }
/// <summary>
        /// 图片链接地址
        /// </summary>
        public List<string> Picture
        {
            set;
            get;
        }

        public DateTime IssueDate
        {
            get
            {
                DateTime dt;
                if (!DateTime.TryParse(Date, out dt))
                    dt=new DateTime(1999, 1, 1, 0, 0, 0);
                return dt;
            }
        }
        public string Author
        {
            get;
            set;
        }
        /// <summary>
        /// 发布时间
        /// </summary>
        public string Date
        {
            get;
            set;
        }
        public bool Save()
        {
            try
            {
                string filepath=Utils.FileBasePath+"/"+this.Title.Trim().Replace("/", "").Replace("\", "")+DateTime.Now.ToString("_MMddHHmmss")+".XML";
                XmlSerializer xs=new XmlSerializer(typeof(Gather_Article));
                FileInfo f=new FileInfo(filepath);
                if (!f.Directory.Exists)
                    f.Directory.Create();
                Stream stream=new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read);
                xs.Serialize(stream, this);
                stream.Close();
                return true;
            }
            catch (System.Exception ex)
            {
                amao.Chart.Log.WriteLog(ex.ToString());
                return false;
            }
        }
        public static Gather_Article Read(string filepath)
        {
            if (HttpRuntime.Cache[filepath]==null)
            {
                Gather_Article gobj=new Gather_Article();
                if (File.Exists(filepath))
                {
                    XmlSerializer xs=new XmlSerializer(typeof(Gather_Article));
                    Stream stream=new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    gobj=xs.Deserialize(stream) as Gather_Article;
                    stream.Close();
                }
                else
                {
                    return null;
                }
                HttpRuntime.Cache.Insert(
                       filepath,
                       gobj,
                       new CacheDependency(filepath),
                       System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1)
                       );
                return gobj;
            }
            else
            {
                return HttpRuntime.Cache[filepath] as Gather_Article;
            }
        }/*      */
        #endregion Model

    }
}

     也可以在类中添加带这样标记的属性,而后在xml中会以 Gather_Article的属性出现 <Gather_Article Url="" Coding="" 

  [XmlAttribute("Url")]
        public string Url
        {
            get;
            set;
        }
        [XmlAttribute("Coding")]
        public string Coding
        {
            get;
            set;
        }

文章出处:http://www.diybl.com/course/4_webprogram/asp.net/asp_netshl/2008430/112161_2.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的序列化和反序列化是用来将对象转换为字节流或从字节流恢复对象的过程。这在数据存储、网络传输和对象持久化方面非常有用。 要进行序列化和反序列化,你可以使用.NET框架中的System.Runtime.Serialization命名空间提供的类。下面是一个简单的示例: 首先,定义一个需要序列化和反序列化的类,假设为Person: ```csharp [Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } } ``` 接下来,我们可以使用BinaryFormatter进行序列化和反序列化。示例代码如下: ```csharp using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; public class Program { public static void Main() { Person person = new Person() { Name = "John", Age = 30 }; // 序列化对象到字节流 byte[] data = Serialize(person); // 反序列化字节流到对象 Person deserializedPerson = Deserialize(data); Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}"); } public static byte[] Serialize(Person obj) { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, obj); return stream.ToArray(); } } public static Person Deserialize(byte[] data) { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream(data)) { return (Person)formatter.Deserialize(stream); } } } ``` 在上述示例中,我们通过Serialize方法将Person对象序列化为字节流,然后通过Deserialize方法将字节流反序列化为Person对象。通过打印反序列化后的Person对象的属性,我们可以验证序列化和反序列化的过程是否成功。 请注意,在进行序列化和反序列化时,类需要标记为可序列化,即使用[Serializable]属性进行标记。 希望这个简单的示例能帮助你理解和实现C#中的序列化和反序列化操作。如果你有更多特定的问题,请随时提问!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值