我正在编写一个小的 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
不公开,但是如果我将它设置为 public xSer.Serialize(fs, this)
以外的任何内容,则不会包含该属性。我需要做什么才能使其正常工作?
我知道还有许多其他类似的问题,但是它们都没有 .NET 2.0 要求,并且使用的解决方案对于仅限于 2.0 的人来说是不可用的。除了编写自定义 XMLSerarlizer
或接受 ProtectedPassword
是公开的事实之外,还有其他选择吗?
最佳答案
据我所知,在 .NET 2.0 中完成此操作的唯一方法是编写 IXmlSerializable
的自定义实现。 .
也就是说,如果配置文件不需要人类可读/可编辑,我建议使用 BinaryFormatter
执行二进制序列化,这将捕获私有(private)成员。
关于c# - 在 .NET 2.0 中序列化私有(private)支持数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11748455/