【发布时间】:2019-01-07 18:19:04
【问题描述】:
我正在使用 C# 和 .NET Framework 4.7 开发一个 WinForm 应用程序。
使用此应用程序,我正在尝试从另一个应用程序加载配置文件:
string applicationName = Environment.GetCommandLineArgs()[1];
if (!string.IsNullOrWhiteSpace(applicationName))
{
if (!applicationName.EndsWith(".exe"))
applicationName += ".exe";
string exePath =
Path.Combine(Environment.CurrentDirectory, applicationName);
try
{
// Get the configuration file. The file name has
// this format appname.exe.config.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(exePath);
但是ConfigurationManager.OpenExeConfiguration(exePath)抛出异常:
An error occurred while loading the configuration file: The 'exePath' parameter is not valid.
Parameter name: exePath
配置文件 AnotherApp.exe.config 存在于文件夹 Environment.CurrentDirectory 中。我也尝试将其更改为 Path.Combine(@"D:\", applicationName); 并得到相同的异常。
如果我在这里的名称末尾添加exe.config,而不是.exe,applicationName += ".exe";,它似乎打开了一些东西:config.FilePath 是D:\AnotherApp.exe.config.config。但是config 对象是空的。它没有填充任何属性。
我做错了什么?
我已经从Microsoft documentation复制了代码。
【问题讨论】:
-
Environment.CurrentDirectory是否指向您预期的正确目录?这个异常看起来好像没有找到AnotherApp.exe.config。可以读取其他exe.config文件。 -
@Subbu 是的。我已经更新了这个问题,因为我试图从 D:\ 加载它,但遇到了同样的问题。
-
您可以尝试使用 ExeConfigurationFileMap 吗? msdn.microsoft.com/en-us/library/…
标签: c# app-config configurationmanager