【问题标题】:Serialize a private backing data member in .NET 2.0?序列化 .NET 2.0 中的私有后备数据成员?
【发布时间】:2012-07-31 20:26:51
【问题描述】:

我正在编写一个小的 xml 配置文件,该文件将从特定位置保存和加载(因此不使用 user.config)。我的应用程序是 .NET 2.0,不能移动到更新的版本(所以没有DataContractSerializer) 我需要实现“保存密码”选项,以便在用户使用应用程序时预先填写密码字段。

目前我是这样做的

public class UserSettings
{
    //Snip many other properties...

    public bool SavePassword { get; set; }

    [XmlIgnore]
    public string Password
    {
        get
        {
            string retVal = string.Empty;
            if (ProtectedPassword != null)
            {
                try
                {
                    retVal = Encoding.UTF8.GetString(ProtectedData.Unprotect(ProtectedPassword, _md5.ComputeHash(Encoding.UTF8.GetBytes(this.Username.ToUpper())), DataProtectionScope.LocalMachine));
                }
                catch
                {
                    retVal = string.Empty;
                }
            }
            return retVal;
        }
        set
        {
            ProtectedPassword = ProtectedData.Protect(Encoding.UTF8.GetBytes(value), _md5.ComputeHash(Encoding.UTF8.GetBytes(this.Username.ToUpper())), DataProtectionScope.LocalMachine);
        }
    }

    public byte[] ProtectedPassword;

    private readonly MD5 _md5 = MD5.Create();


    public void Save()
    {
        var xOver = new XmlAttributeOverrides();

        //If Save password is false do not store the encrypted password
        if (this.SavePassword == false)
        {
            var xAttrs = new XmlAttributes();
            xAttrs.XmlIgnore = true;
            xOver.Add(typeof(UserSettings), "ProtectedPassword", xAttrs);
        }

        XmlSerializer xSer = new XmlSerializer(typeof(UserSettings), xOver);
        Directory.CreateDirectory(Path.GetDirectoryName(savePath));
        using(var fs = new FileStream(savePath, FileMode.Create))
        {
            xSer.Serialize(fs, this);
        }

    }

我想让ProtectedPassword 不公开,但是如果我将其设置为公开以外的任何内容xSer.Serialize(fs, this) 将不包含该属性。我需要做什么才能使这项工作正常进行?

我知道还有很多其他类似的问题,但是它们都没有 .NET 2.0 的要求,并且使用的解决方案对于受限于 2.0 的人来说是不可用的。除了编写自定义XMLSerarlizer 或接受ProtectedPassword 是公开的事实之外,还有其他选择吗?

【问题讨论】:

    标签: c# xml serialization .net-2.0 private-members


    【解决方案1】:

    据我所知,在 .NET 2.0 中完成此操作的唯一方法是编写 IXmlSerializable 的自定义实现。

    也就是说,如果配置文件不需要人类可读/可编辑,我建议使用BinaryFormatter 执行二进制序列化,这将捕获私有成员。

    【讨论】:

    猜你喜欢
    • 2010-10-22
    • 2020-09-04
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 2015-02-11
    • 1970-01-01
    相关资源
    最近更新 更多