在安装程序类中编辑自定义配置部分

4
我正在尝试在自定义操作安装过程中更新Web.config文件的自定义配置部分。我想使用实际的配置类来完成此操作,但是当安装程序运行时,它加载我的安装程序类,但Configuration.GetSection抛出一个“文件未找到”异常,因为它正在尝试从Windows系统目录加载我的自定义部分类。我设法通过将所需的程序集复制到Windows系统目录中使其正常工作,但这不是理想的解决方案,因为我不能保证我始终都能访问该目录。

还有什么其他方法可以解决这个问题吗?

我的更新代码如下:

[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
    public override void Install(System.Collections.IDictionary stateSaver)
    {
        //some code here
        webConfig = WebConfigurationManager.OpenWebConfiguration("MyService");
        MyCustomSection mySection = webconfig.GetSection("MyCustomSection") //<--File Not Found: CustomConfigSections.dll
        //Update config section and save config
    }
}

我的配置文件长这样:
<configuration>
    <configSections>
        <section name="myCustomSection" type="CustomConfigSections.MyCustomSection, CustomConfigSections" />
     </configSections>
    <myCustomSection>
        <!-- some config here -->
    </myCustomSection>
</configuration>

你解决了吗?我也遇到了同样的问题。我可以正常访问AppSettings,但是加载ConfigHandler所需的DLL是安装的一部分,虽然似乎存在于文件夹中,但无法访问。我认为这可能有所帮助,但目前还没有成功:AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); - Rebecca
我找到了另一个稍微好一点的解决方案。你可以使用Orca编辑msi文件,改变它执行任务的顺序,这样在自定义操作运行之前就可以部署程序集并将其放入GAC中。虽然仍不是理想的解决方案,但比以前要好。 - John Hunter
1个回答

1
希望您能理解答案的意图。
假设您已经设置安装程序以输出项目。如果没有,请右键单击安装程序项目,点击添加-> 项目输出-> 选择您的项目,然后您可以继续使用您的代码。
此外,如果您正在使用除 .net 之外的 dll,请确保将它们的属性更改为 copylocal = true。
如果您想在安装之前读取元素,请使用 BeforeInstall 事件处理程序并尝试读取文件。我希望您的问题会得到解决。
如果您想在安装后读取元素,请右键单击安装程序项目,点击查看-> 自定义操作-> 在安装时单击添加自定义操作-> 选择应用程序文件夹-> 从您的项目中选择主要输出,然后单击确定。
现在单击主要输出并按 F4,在自定义操作数据中编写。
/DIR="[TARGETDIR]\"

然后按照以下方式编写您的代码。
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
  public ProjectInstaller()
  {
    this.InitializeComponent();
  }
  private void InitializeComponent()
  {
    this.AfterInstall += new InstallEventHandler(ProjectInstaller_AfterInstall);
  }
  void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
  {
    string path = this.Context.Parameters["DIR"] + "YourFileName.config";
    // make sure you replace your filename with the filename you actually
    // want to read
    // Then You can read your config using XML to Linq Or you can use
    // WebConfigurationManager whilst omitting the .config from the path
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接