I am writing a small xml configuration file that will be saved and loaded from a specific location (so do not use user.config ). My application is .NET 2.0 and cannot be ported to a newer version (therefore there is no DataContractSerializer ). I need to implement the "Save Password" option so that the password field is pre-populated when the user uses the application.
Now, this is how I do it
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); } }
I would like to make ProtectedPassword not public, however, if I set it to anything other than public xSer.Serialize(fs, this) , it will not include the property. What do I need to do to make this work right?
I know that there are many other similar issues, but none of them have the requirements of .NET 2.0 and do not use solutions that are not available to a person who is limited to 2.0. Is there any option other than writing a custom XMLSerarlizer or living with the fact that ProtectedPassword is publicly available.
source share