c# – 在.NET 2.0中序列化私有后备数据成员?

c# – 在.NET 2.0中序列化私有后备数据成员?,第1张

概述我正在编写一个小的xml配置文件,该文件将从特定位置保存和加载(因此不使用user.config).我的应用程序是.NET 2.0,无法移动到更新版本(因此没有DataContractSerializer)我需要实现“保存密码”选项,以便在用户使用应用程序时预先填写密码字段. 目前我就是这样做的 public class UserSettings{ //Snip many other p 我正在编写一个小的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),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是公共的这一事实之外,还有其他选择吗?

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

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

总结

以上是内存溢出为你收集整理的c# – 在.NET 2.0中序列化私有后备数据成员?全部内容,希望文章能够帮你解决c# – 在.NET 2.0中序列化私有后备数据成员?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1234833.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存