Updating a config file in c#

2019-09-05 02:45发布

问题:

I am creating an update to my companies system that will be running on several clients and I have two config files, the old config file and the newer version. Is there any way that I can compare the both files and check the differences to add to the older file what I have new in the first one? Keep in mind that the files may have different info and the only thing that I need to add/change is the keys. For example, if a key is different change the older to that new "version", if a key doesn’t exist in the older files add it.

they keys will have the exact same name but may have different values. Plus there could be a new key that doesnt exist in the older file and I need to add it

I will leave an example of the files for you to see,

Any help would be appreciated.

<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>

回答1:

Code went like this and it works like a charm:

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!";
        }

}