我有一个具有以下结构的 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 可以被任何其他应用程序使用,而其他应用程序可能没有定义该类。
最佳答案
作为一个选项,您可以将 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]\"
就足够了,然后在安装程序类中,您可以使用 轻松获取它上下文参数["路径"]
。然后另一方面,您知道 dll 文件的名称并通过将配置文件地址作为参数传递来使用 OpenMappedExeConfiguration
,读取设置。
要设置自定义安装程序操作并获取目标目录,您可能会发现此分步答案很有用:Visual Studio Setup Project - Remove files created at runtime when uninstall .
关于c# - 在卸载期间(卸载前)从自定义安装程序获取对 AppSettings 的访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57316014/