使用c#在安装时修改App.Config文件

时间:2010-08-31 11:42:41

标签: c#

<configuration>
  <configSections>
    <section name="ADMIN" type="System.Configuration.DictionarySectionHandler"/>
  </configSections>
  <User>    
    <add key="ExtendTime" value="20"/>
    <add key="Name" value="sss"/>
  </User>
<configuration>

我必须删除用户配置部分中的第一个子元素,即。如果您对此有任何想法,请回复我。

我正在使用

Configuration config = ConfigurationManager.OpenExeConfiguration(Context.Parameters["assemblypath"]);
ConfigurationSection section = config.GetSection("USER");

3 个答案:

答案 0 :(得分:3)

这篇文章可能包含您所需要的内容:http://raquila.com/software/configure-app-config-application-settings-during-msi-install/

摘自文章:

string exePath = string.Format("{0}MyWindowsFormsApplication.exe", targetDirectory);
Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
config.AppSettings.Settings["Param1"].Value = param1;
config.AppSettings.Settings["Param2"].Value = param2;
config.AppSettings.Settings["Param3"].Value = param3;
config.Save();

编辑:添加其他代码示例和博客参考:http://ryanfarley.com/blog/archive/2004/07/13/879.aspx

using System;
using System.Xml;  
using System.Configuration;
using System.Reflection;
//...


public class ConfigSettings
{
    private ConfigSettings() {}

    public static string ReadSetting(string key)
    {
        return ConfigurationSettings.AppSettings[key];
    }

    public static void WriteSetting(string key, string value)
    {
        // load config document for current assembly
        XmlDocument doc = loadConfigDocument();

        // retrieve appSettings node
        XmlNode node =  doc.SelectSingleNode("//appSettings");

        if (node == null)
            throw new InvalidOperationException("appSettings section not found in config file.");

        try
        {
            // select the 'add' element that contains the key
            XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));

            if (elem != null)
            {
                // add value for key
                elem.SetAttribute("value", value);
            }
            else
            {
                // key was not found so create the 'add' element 
                // and set it's key/value attributes 
                elem = doc.CreateElement("add");
                elem.SetAttribute("key", key);
                elem.SetAttribute("value", value); 
                node.AppendChild(elem);
            }
            doc.Save(getConfigFilePath());
        }
        catch
        {
            throw;
        }
    }

    public static void RemoveSetting(string key)
    {
        // load config document for current assembly
        XmlDocument doc = loadConfigDocument();

        // retrieve appSettings node
        XmlNode node =  doc.SelectSingleNode("//appSettings");

        try
        {
            if (node == null)
                throw new InvalidOperationException("appSettings section not found in config file.");
            else
            {
                // remove 'add' element with coresponding key
                node.RemoveChild(node.SelectSingleNode(string.Format("//add[@key='{0}']", key)));
                doc.Save(getConfigFilePath());
            }
        }
        catch (NullReferenceException e)
        {
            throw new Exception(string.Format("The key {0} does not exist.", key), e);
        }
    }

    private static XmlDocument loadConfigDocument()
    {
        XmlDocument doc = null;
        try
        {
            doc = new XmlDocument();
            doc.Load(getConfigFilePath());
            return doc;
        }
        catch (System.IO.FileNotFoundException e)
        {
            throw new Exception("No configuration file found.", e);
        }
    }

    private static string getConfigFilePath()
    {
        return Assembly.GetExecutingAssembly().Location + ".config";
    }
}

然后你会像这样使用它:

// read the Test1 value from the config file
string test1 = ConfigSettings.ReadSetting("Test1");

// write a new value for the Test1 setting
ConfigSettings.WriteSetting("Test1", "This is my new value");

// remove the Test1 setting from the config file
ConfigSettings.RemoveSetting("Test1");

答案 1 :(得分:0)

我得出的结论是,在安装过程中无法使用以下方式访问自定义配置部分:

MyCustomConfigurationSection section = (MyCustomConfigurationSection)config.GetSection("MyCustomConfigurationSection");

安装MSI软件包时,执行的程序是Windows Install(MsiExec),而不是包含安装程序类的程序。

'%windir%\system32\msiexec.exe

要访问配置,我们需要使用上下文来解决此问题:

Configuration config = ConfigurationManager.OpenExeConfiguration(this.Context.Parameters["assemblypath"]);

或者,通过使用反射检索执行程序集的位置:

Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);

正如Chuck建议的那样,您可以访问AppSettings并修改它们:

AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
appSettings.Settings["Environment"].Value = _Environment;
config.Save();

这很好,因为安装人员确切知道如何处理

System.Configuration.AppSettingsSection

因为该库是.NET的一部分。但是,当涉及到自定义部分时,安装程​​序需要知道如何处理该自定义配置。更有可能的是,您将它放在应用程序引用的类库(在DLL中)中,并且该DLL现在已安装在安装目录中。

问题是,正如我们从上面所知,MSIExec.exe没有在该目录的上下文中运行,因此安装失败,当它在system32中找不到合适的DLL时,它会抛出错误:< / p>

  

创建时出错   配置节处理程序   'XXX':无法加载文件或程序集   'XXX.dll'或其依赖项之一。   系统找不到该文件   指定。

因此,访问自定义配置的唯一方法是将配置文件视为XML文档,并使用传统的XML管理工具对其进行编辑:

// load the doc
XmlDocument doc = new XmlDocument();
doc.Load(Assembly.GetExecutingAssembly().Location + ".config");

// Get the node
XmlNode node =  doc.SelectSingleNode("//MyCustomConfigurationSection");

// edit node here
// ...

// Save
doc.Save(Assembly.GetExecutingAssembly().Location + ".config");

这项技术在Ryan Farley's blog中有所描述,正如查克在对原始答案的评论中指出的那样。

答案 2 :(得分:0)

好消息!我找到了解决这个问题的方法。 解决方案是拦截装配的装载并返回我们拥有的装配。这样做

ResolveEventHandler handler = new ResolveEventHandler(CurrentDomain_AssemblyResolve);
AppDomain.CurrentDomain.AssemblyResolve += handler;
try
{
   section = config.GetSection("mySection") as MySection;
}
catch(Exception)
{
}
AppDomain.CurrentDomain.AssemblyResolve -= handler;

Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    if (args.Name == "Dead.Beef.Rocks")
    {
        return typeof(MySection).Assembly;
    }
    return null;
}