我正在尝试在我的设置和部署项目中调用自定义操作,以更新我的应用上 app.config 中的一些项目。我已经以通常的方式结束了自定义配置部分,例如:
[ConfigurationProperty("serviceProvider", IsRequired = true)]
public string ServiceProvider
{
get { return (string)base["serviceProvider"]; }
set { base["dataProviderFactory"] = value; }
}
我已将自定义操作设置为在安装的安装部分中调用,就在 base.Install(stateSaver) 之后。代码是:
string exePath = string.Format("{0} MyApp.exe", Context.Parameters["DP_TargetDir"]);
SysConfig.Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
Configuration. MyApp section = Configuration.MyApp)config.GetSection("MyApp");
当我运行这个时,我得到这个错误:
System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for MyApp: Could not load file or assembly 'MyCompany. MyApp.Configuration' or one of its dependencies. The system cannot find the file specified. (C:\Program Files\MyCompany\MyApp\MyApp.exe.config line 5) ---> System.IO.FileNotFoundException: Could not load file or assembly 'MyCompany.MyApp.Configuration' or one of its dependencies. The system cannot find the file specified.
配置中的第 5 行是:
<section name="MyApp"
type="MyCompany.MyApp.Configuration.MyApp, MyCompany.MyApp.Configuration"
requirePermission="false" />
带有安装程序代码的类库(该库中唯一的类)具有对配置程序集的引用。
我在这里遗漏了什么非常明显的东西吗?我无法弄清楚为什么找不到配置的引用。
非常感谢任何帮助/建议。
最佳答案
我设法在 MSDN 上找到了一些代码,这些代码提供了一种有效的(尽管被黑了)方法来做到这一点。链接在这里:ConfigurationManager, custom config, and installutil / path searching problem .
如果不是因为能够在建议的帮助下进行调试,就不会找到它,所以感谢你们俩。
作为引用,我的最终安装代码是:
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
string targetDirectory = Context.Parameters["DP_TargetDir"];
stateSaver.Add("TargetDir", targetDirectory);
string exePath = Path.Combine(targetDirectory, "MyApp.exe");
System.Diagnostics.Debugger.Break();
ResolveEventHandler tempResolveEventHandler =
(sender, args) =>
{
string simpleName = new AssemblyName(args.Name).Name;
string path = Path.Combine(targetDirectory, simpleName + ".dll");
return File.Exists(path)
? Assembly.LoadFrom(path)
: null;
};
try
{
// hook up asm resolve handler
AppDomain.CurrentDomain.AssemblyResolve += tempResolveEventHandler;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
Configuration.MyApp section = (Configuration.MyApp) config.Sections["MyApp"];
if (section != null)
{
// "ApplicationSettings.DefaultDatabasePath" is the custom config value I'm updating
section.ApplicationSettings.DefaultDatabasePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
config.Save();
}
}
finally
{
// remove asm resolve handler.
AppDomain.CurrentDomain.AssemblyResolve -= tempResolveEventHandler;
}
}
关于.net - 尝试加载自定义配置时 Visual Studio 安装和部署项目中的 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1587911/