我有一个具有以下结构的VS解决方案:
库项目(.dll)
使用#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可以被任何其他应用程序使用,并且其他应用程序可能未定义该类。
答案 0 :(得分: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]\"
就足够了,然后在installer类中,您可以使用Context.Parameters["path"]
轻松获得它。然后,另一方面,您知道dll文件的名称,并通过将配置文件地址作为参数使用OpenMappedExeConfiguration
来读取设置。
要设置自定义安装程序操作并获取目标目录,您可能会发现此分步解答很有用:Visual Studio Setup Project - Remove files created at runtime when uninstall。