/*下面不能把Color属性的值写到 myinfo.config文件中,为什么?*/
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {  
        
        string fileName = HttpContext.Current.Server.MapPath("~/myinfo.Config");        protected void Page_Load(object sender, EventArgs e)
        {
            MyInfo myInfo = new MyInfo();
            myInfo.Color = Color.Blue;
            myInfo.FontStyle = FontStyle.Strikeout | FontStyle.Bold | FontStyle.Italic;
            myInfo.Name = "yuna123";
            SetMyInfo(myInfo);            MyInfo info = GetMyInfo();
            Response.Write(info.Name); Response.Write("<br/>");
            Response.Write(info.Color); Response.Write("<br/>");
            Response.Write(info.FontStyle); Response.Write("<br/>"); 
        }
        // 获取信息
        public MyInfo GetMyInfo()
        {
            MyInfo info;
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(MyInfo));
               
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                info = (MyInfo)serializer.Deserialize(fs);
                fs.Close();
            }
            catch
            {
                info = new MyInfo();
            }
            return info;
        }
        // 设置信息
        public void SetMyInfo(MyInfo info)
        {
            try
            {
                FileStream stream = new FileStream(this.fileName, FileMode.Create, FileAccess.Write);
                XmlSerializer serializer = new XmlSerializer(typeof(MyInfo));
                serializer.Serialize(stream, info);
                stream.Close();
            }
            catch { }
        }
    }
    public class MyInfo
    {
        string _name;
        Color _color;
        FontStyle _fontStyle;
        
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }        public Color Color
        {
            get { return this._color; }
            set { this._color = value; }
        }        public FontStyle FontStyle
        {
            get { return this._fontStyle; }
            set { this._fontStyle = value; }
        }
    }
}

解决方案 »

  1.   

    [Serializable]
     public class MyInfo:ISerializable XmlSerializer xSerial = new XmlSerializer(typeof(MyInfo));
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(@"D:\a.xml", FileMode.Open, FileAccess.Read, FileShare.None);
            object obj = formatter.Deserialize(stream);
            stream.Close();
      

  2.   

    测试了一下,正常的。注意一点。你的MyInfo不能定义在某个静态类中。检查一下你MyInfo定义的位置。