在c#中更新配置文件

Updating a config file in c#

我正在为我公司的系统创建一个更新,它将在多个客户端上 运行 并且我有两个配置文件,旧配置文件和新版本。 有什么方法可以比较这两个文件并检查差异以将第一个文件中的新内容添加到旧文件中? 请记住,这些文件可能有不同的信息,我唯一需要 add/change 的就是密钥。例如,如果密钥不同,则将旧文件更改为新文件 "version",如果旧文件中不存在密钥,则添加它。

它们的键将具有完全相同的名称,但可能具有不同的值。另外可能有一个旧文件中不存在的新密钥,我需要添加它

我会留下一个文件的例子给你看,

如有任何帮助,我们将不胜感激。

<configuration>
  <appSettings>
    <add key="ORCASRV1"            value="ORCA30|tcp://127.0.0.1:9001" />
    <add key="ORCASRV2"            value="REORCA30|tcp://127.0.0.1:9001" />
    <add key="ServidorEmail"       value="xxx" />
    <add key="SqlTrans"            value="1" />
    <add key="RemoteType"          value="0" />
    <add key="LocalPort"           value="9002" />
    <add key="LocalMsgStore"       value="1" />
    <add key="sqlCHAR_TO_DATA"     value="CONVERT(datetime, '#MM#/#DD#/#YYYY#')" />
    <add key="sqlDATA_TO_CHAR"     value="CONVERT(char(30), #CAMPO#)" />
    <add key="sqlDATAPARTE"        value="LTRIM(STR(DATEPART(#PARTE, #CAMPO#)))" />
    <add key="sqlNUM_TO_CHAR"      value="LTRIM(STR(#VALOR#))" />
    <add key="sqlSYSDATE"          value=" GetDate() " />
    <add key="sqlALIAS"            value=" As " />
    <add key="sqlCONCATENAR"       value="+" />    <add key="sqlNULL"             value="IsNull(#CAMPO#,#VALOR#)" />
    <add key="sqlROUND"            value="ROUND(#CAMPO#,#PARTE#)" />
    <add key="sqlLPAD"             value="RIGTH(REPLICATE('#CHAR#',#VEZES#)+#CAMPO#,#VEZES#)" />
    <add key="oraCHAR_TO_DATA"     value="TO_DATE('#MM#/#DD#/#YYYY#','MM/DD/YYYY')" />
    <add key="oraDATA_TO_CHAR"     value="TO_CHAR(#CAMPO#, 'DD/MM/YYYY')" />
    <add key="oraDATAPARTE"        value="TO_CHAR(#PARTE#, #CAMPO#)" />
    <add key="oraNUM_TO_CHAR"      value="TO_CHAR(#VALOR#)" />
    <add key="oraSYSDATE"          value=" SYSDATE " />
    <add key="oraALIAS"            value=" " />
    <add key="oraCONCATENAR"       value="||" />
    <add key="oraNULL"             value="NVL(#CAMPO#,#VALOR#)" />
    <add key="oraROUND"            value="ROUND(#CAMPO#,#PARTE#)" />
    <add key="oraLPAD"             value="LPAD(#CAMPO#,#VEZES#,#CHAR#)" />
    <add key="EmailCDP"            value="antonio.santos@cdp-si.pt" />
    <add key="EmailCliente"        value="xxx" />
    <add key="RPT_PATH1"           value="C:\PROD\ORCAREPORT\" />
    <add key="StartPage_Height"    value="90" />
    <add key="StartPage_Margem"    value="220" />
    <add key="StartPage_Espaco"    value="5" />
    <add key="StartPage_Intervalo" value="2" />
    <add key="StartPage_Mais"      value="35" />
    <add key="HelpExec"            value="WINHLP32.EXE" />
    <add key="HelpFile"            value="ORCA.HLP" />
    <add key="LogLevel"            value="0" />
    <add key="LogSqlClient"        value="0" />
    <add key="LogFile"             value="C:\cdpsi\logs" />
  </appSettings>
  <system.runtime.remoting>
    <application>
      <channels>
        <channel ref="tcp" port="9002">
          <clientProviders>
            <formatter ref="binary" />            <provider type="CdpCompress.CompressionClientSinkProvider, CdpCompress" />
          </clientProviders>
        </channel>
      </channels>
    </application>
  </system.runtime.remoting>
</configuration>

代码是这样的,它的工作原理非常棒:

public void UpdateService(string FilePathOld, string FilePathNew, string LatestVersion)
{
        Dictionary<string, string> Old = new Dictionary<string, string>();
        Dictionary<string, string> New = new Dictionary<string, string>();

        if (ExisteFicheiro(FilePathNew) == true && ExisteFicheiro(FilePathOld) == true)
        {
            ExeConfigurationFileMap configOld = new ExeConfigurationFileMap();
            configOld.ExeConfigFilename = FilePathOld;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configOld, ConfigurationUserLevel.None);

            ExeConfigurationFileMap configNew = new ExeConfigurationFileMap();
            configNew.ExeConfigFilename = FilePathNew;
            Configuration config2 = ConfigurationManager.OpenMappedExeConfiguration(configNew, ConfigurationUserLevel.None);

            KeyValueConfigurationCollection settings = config.AppSettings.Settings;
            Old = settings.AllKeys.ToDictionary(key => key, key => settings[key].Value);
            KeyValueConfigurationCollection settings2 = config2.AppSettings.Settings;
            New = settings2.AllKeys.ToDictionary(key => key, key => settings2[key].Value);

            foreach (var NewKey in New)
            {
                string value;
                if (Old.TryGetValue(NewKey.Key, out value))
                {
                    if (value != NewKey.Value)
                    {
                        //if (ExistsKey(NewKey.Key, false) == true)
                        Old[NewKey.Key] = NewKey.Value;

                    }
                }
                else
                {
                    Old.Add(NewKey.Key, NewKey.Value);
                }
            }

            foreach (var NewKey in Old)
            {
                string key = NewKey.Key;
                string value = NewKey.Value;
                if (config.AppSettings.Settings[key] != null)
                {
                    config.AppSettings.Settings[key].Value = value;
                    if (key == "Version")
                        config.AppSettings.Settings[key].Value = LatestVersion;
                }
                else
                {
                    config.AppSettings.Settings.Add(key, value);

                }
                if (config.AppSettings.Settings["Version"] == null)
                {
                    config.AppSettings.Settings.Add("Version", LatestVersion);
                }

            }
            config.Save();
        }
        else
        {
            Erro NovoErro = new Erro();
            Global.Erro = "O ficheiro \"OrcaService.exe.config\" ou o ficheiro \"Orca.exe.config\" não existem nos caminhos especificados!";
        }

}