加密XML自定义配置文件



我有这个方法从我的XML "自定义配置"配置文件中填充一个对象:

public static BindingList<StationConfiguration> GetStationsFromConfigFile()
{
    string xmlDocumentText = File.ReadAllText(GetConfigFilePath());
    var doc = new XmlDocument();
    doc.LoadXml(xmlDocumentText);
    BindingList<StationConfiguration> stations = new BindingList<StationConfiguration>();
    foreach (XmlNode node in doc.DocumentElement["StationsSection"].ChildNodes[0].ChildNodes)
    {
        stations.Add(
            new StationConfiguration(
                node.Attributes["Comment"].Value
                , node.Attributes["FtpUsername"].Value
                , node.Attributes["FtpPassword"].Value
                , node.Attributes["DestinationFolderPath"].Value
            ));
    }
    return stations;
}

如您所见,我使用File.ReadAllText将XML配置文件的内容拉入String。

对于未加密的配置文件,这一切都很有效。但现在我需要加密它。MSDN建议这样做:

System.Configuration.Configuration config =
    ConfigurationManager.OpenExeConfiguration(
    ConfigurationUserLevel.None);

(顺便说一下,当我查看config.FilePath属性时,它向我显示了XML配置文件的正确路径,只是有一个额外的"。因为一些奇怪的原因。它以".exe.config"结尾。config"因为一些奇怪的原因。但是我离题了…)

这是我的StationConfigurationSection课:

public class StationConfigurationSection : ConfigurationSection
{
    [ConfigurationProperty("Stations", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(StationCollection),
        AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]
    public StationCollection Stations
    {
        get
        {
            return (StationCollection)base["Stations"];
        }
    }
    public override bool IsReadOnly()
    {
        return false;
    }
}

完整的XML配置文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="StationsSection" type="EcFtpClient.StationConfigurationSection, EcFtpClient" />
  </configSections>
  <StationsSection>
    <Stations>
      <add Comment="ABC" FtpUsername="eliezer" FtpPassword="secret" DestinationFolderPath="C:UserseliezerDesktoplocal dest" FtpTimeoutInSeconds="30" FtpHostname="ftp://192.168.1.100/" FtpFolderPath="" />
    </Stations>
  </StationsSection>
  <startup>
    <supportedRuntime version="v2.0.50727" />
  </startup>
  <appSettings>
    <add key="NameOfService" value="ECClient" />
    <add key="PollingFrequencyInSeconds" value="60" />
  </appSettings>
</configuration>

我想使用MSDN System.Configuration方法,因为它使加密/解密非常容易,但是我如何将他们的方法与我必须使其工作的方法相结合?



我已经有加载的文件,但仍然卡住了,当它涉及到保存文件。

我已经改变了加载方法(在这个问题的最上面)为:

public static BindingList<StationConfiguration> GetStationsFromConfigFile()
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(GetConfigFilePath());
    StationConfigurationSection stationsConfig = (StationConfigurationSection)config.GetSection("StationsSection");
    var stationCollection = ((StationCollection)stationsConfig.Stations);
    BindingList<StationConfiguration> stationsToReturn = new BindingList<StationConfiguration>();
    for (int index = 0; index < stationCollection.Count; index++)
    {
        stationsToReturn.Add(
            new StationConfiguration(
                stationCollection[index].Comment,
                stationCollection[index].FtpUsername,
                stationCollection[index].FtpPassword,
                stationCollection[index].DestinationFolderPath)
            );
    return stationsToReturn;
}

我得到的是加载文件的能力,无论它是否加密-它加载成功。太好了。

但是我仍然不确定如何让储蓄工作。这是我的保存方法:

public static void SaveStationsToConfigFile(BindingList<StationConfiguration> updatedStations, bool isConfigToBeEncrypted)
{
    string configFilePath = GetConfigFilePath();
    var xDoc = XDocument.Load(configFilePath);
    var xDeclaration = xDoc.Declaration;
    var xElement = xDoc.XPathSelectElement("//StationsSection/Stations");
    // clear out existing station configurations
    xDoc.Descendants("Stations").Nodes().Remove();
    foreach (var station in updatedStations)
    {
        xElement.Add(new XElement("add",
                new XAttribute("Comment", station.Station),
                new XAttribute("FtpUsername", station.Username),
                new XAttribute("FtpPassword", station.Password),
                new XAttribute("DestinationFolderPath", station.FolderName),
                new XAttribute("FtpTimeoutInSeconds", 30),
                new XAttribute("FtpHostname", GetEnvironmentAppropriateFtpHostName()),
                new XAttribute("FtpFolderPath", GetEnvironmentAppropriateFtpFolderPath())
        ));
    }
    xDoc.Declaration = xDeclaration;
    xDoc.Save(configFilePath);
}
为了用保护/加密保存它,我需要这样做——换句话说,使用System.Configuration.Configuration对象:
stationsConfig.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
stationsConfig.SectionInformation.ForceSave = true;
objConfig.Save(ConfigurationSaveMode.Modified);

但我目前仍在做保存与XDocument.Save

是否有办法将我的XDocument转换为System.Configuration.Configuration兼容的对象?
想到的hack是在调用XDocument.Save之后-加载它并使用System.Configuration.Configuration的东西再次保存它。

我相信您必须使用配置设置框架。您不需要尝试自己打开xml文件,而是需要创建ConfigurationSection的后代。

这样,它将为您读取和写入加密配置。

看起来您已经启动了路由(EcFtpClient.StationConfigurationSection),但是您没有包含任何代码。

最新更新