【问题标题】:Trying to open another's application configuration file试图打开其他人的应用程序配置文件
【发布时间】: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,而不是.exeapplicationName += ".exe";,它似乎打开了一些东西:config.FilePathD:\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


【解决方案1】:

在尝试打开AnotherApp.exe.config 之前,ConfigurationManager.OpenExeConfiguration 检查磁盘上是否存在AnotherApp.exe。这是source

// ...
else {
    applicationUri = Path.GetFullPath(exePath);
    if (!FileUtil.FileExists(applicationUri, false))
        throw ExceptionUtil.ParameterInvalid("exePath");

    applicationFilename = applicationUri;
}

// Fallback if we haven't set the app config file path yet.
if (_applicationConfigUri == null) {
    _applicationConfigUri = applicationUri + ConfigExtension;
}

如您所见,exePath 最终被传递到FileUtils.FileExists,它最终检查exePath 是否代表磁盘上的文件。在您的情况下,这是AnotherApp.exe 存在。 throw ExceptionUtil.ParameterInvalid("exePath"); 语句是您的错误的来源。

在我上面包含的源代码的更下方,您可以看到 _applicationConfigUri 设置为 AnotherApp.exe.config(这是一个绝对路径,但为了简单起见,我使用了相对路径)。当您将exePath 设置为AnotherApp.exe.config 时,代码最终会检查是否存在AnotherApp.exe.config(它认为这是exe 本身),它会找到它。在此之后,_applicationConfigUri 设置为 AnotherApp.exe.config.config,这 存在,但在这种情况下配置系统不会出错(而是返回一个空的配置对象)。

看来解决这个问题可能有两种选择:

  1. AnotherApp.exe.config 旁边添加AnotherApp.exe
  2. 使用ConfigurationManager.OpenMappedExeConfiguration,它允许您提供自己的ExeConfigurationFileMap,用于指导配置系统如何定位.config 文件。如果您需要这方面的帮助,请告诉我,我将举例说明这应该如何工作。

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多