【问题标题】:Get access to AppSettings from custom Installer during uninstall (BeforeUninstall)在卸载期间从自定义安装程序访问 AppSettings (BeforeUninstall)
【发布时间】:2019-08-01 19:43:28
【问题描述】:

我有一个具有以下结构的 VS 解决方案:

  1. 库项目 (.dll)

  2. 使用 #1 库项目的应用程序

我在应用程序 (#2) 中定义了 app.config,它在 appSettings 中定义了 SaveLogsToDirectory 路径。这个值最终被库项目用来保存生成的日志。

api的简单使用System.Configuration.ConfigurationManager.AppSettings["SaveLogsToDirectory"] 在库中从 app.config 中获取值。

库项目定义了一个自定义的System.Configuration.Install.Installer 类。当通过控制面板从 Windows 卸载应用程序时,我希望删除路径 SaveLogsToDirectory 处生成的日志。问题是以下代码仅在卸载执行期间返回 null

System.Configuration.ConfigurationManager.AppSettings["SaveLogsToDirectory"]

我尝试过的其他方法之一是使用System.Configuration.ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly())

但在卸载过程中,api Assembly.GetExecutingAssembly() 返回对库项目的引用。

我需要有关如何在卸载期间从库中访问应用程序程序集的帮助?值得一提的是,我无法将应用程序中定义的类路径提供给 OpenExeConfiguration api,因为任何其他应用程序都可以使用该 dll,并且其他应用程序可能没有定义该类。

【问题讨论】:

  • 安装程序知道安装目录。问题是,它不知道配置文件名。作为一个选项,您可以将设置存储在 dll 的配置文件中。这样安装程序也会知道配置文件名(yourdll.config)并可以使用它。

标签: c# .net winforms setup-deployment appsettings


【解决方案1】:

作为一个选项,您可以将 dll 设置存储在 dll 的配置文件中,而不是应用程序的配置文件中。

然后你就可以很方便地使用OpenExeConfiguration,将dll地址作为参数传递并读取设置。

为了使从应用设置中读取更容易和更和谐,您可以创建一个类似的关注者并以这种方式使用它:LibrarySettings.AppSettings["something"]。这是一个简单的实现:

using System.Collections.Specialized;
using System.Configuration;
using System.Reflection;
public class LibrarySettings
{
    private static NameValueCollection appSettings;
    public static NameValueCollection AppSettings
    {
        get
        {
            if (appSettings == null)
            {
                appSettings = new NameValueCollection();
                var assemblyLocation = Assembly.GetExecutingAssembly().Location;
                var config = ConfigurationManager.OpenExeConfiguration(assemblyLocation);
                foreach (var key in config.AppSettings.Settings.AllKeys)
                    appSettings.Add(key, config.AppSettings.Settings[key].Value);
            }
            return appSettings;
        }
    }
}

注意事项:如果您不想在卸载运行时依赖Assembly.ExecutingAssembly,您可以轻松使用指定安装目录的TARGETDIR 属性。将自定义操作的CustomActionData 属性设置为/path="[TARGETDIR]\" 就足够了,然后在安装程序类中,您可以使用Context.Parameters["path"] 轻松获取它。然后另一方面,您知道 dll 文件的名称,并通过传递配置文件地址作为参数使用OpenMappedExeConfiguration,读取设置。

要设置自定义安装程序操作并获取目标目录,您可能会发现此分步回答很有用:Visual Studio Setup Project - Remove files created at runtime when uninstall

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多