在C#中更新配置文件 [英] Updating a config file in c#

查看:125
本文介绍了在C#中更新配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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,

任何帮助将不胜感激。

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


推荐答案

代码就像这样,它就像一个符咒:

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

}

这篇关于在C#中更新配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆