在卸载期间从自定义安装程序访问应用设置(卸载之前)



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

  1. 图书馆项目 (.dll)

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

我在应用程序中定义了app.config,它在appSettings中定义了SaveLogsToDirectory路径。库项目最终使用此值来保存生成的日志。

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

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

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

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

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

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

作为一个选项,您可以将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 安装项目 - 卸载时删除运行时创建的文件。

最新更新