【问题标题】:exePath must be specified when not running inside a stand alone exe不在独立 exe 中运行时必须指定 exePath
【发布时间】:2013-05-19 04:55:45
【问题描述】:

当我使用网络应用程序时,下面的代码行

Configuration objConfig = 
    ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None);

在类库中出现此错误:

"当不在独立 exe 中运行时,必须指定 exePath。"

之前使用的是控制台应用程序,代码可以访问app.config。我尝试在类库中使用System.Web.Configuration,但 .Net 选项卡中不存在“添加引用”的 dll。

请帮助:)

【问题讨论】:

  • 您使用的是哪个版本的 .NET Framework?
  • @wgraham Web 应用程序在 .net 4.0 中,类库在 3.5 中
  • 这是你有源的类库,还是第三方库?

标签: c# web-config app-config


【解决方案1】:

您需要在网络环境中使用不同的配置管理器。以下代码 块显示了如何处理此问题的示例:

System.Configuration.Configuration configuration = null;         
if (System.Web.HttpContext.Current != null)
{
   configuration =
       System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
  configuration =
      ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}

【讨论】:

  • 我相信“~”应该是“~/”(“~”对我不起作用)
  • 我不敢相信这太糟糕了。我绝对不想在我正在执行此操作的地方引用 System.Web。
  • 有些情况HttpContent为null,但你仍然需要调用WebConfigurationManager,例如实际运行在单独线程中的任务,例如HostingEnvironment.QueueBackgroundWorkItem
【解决方案2】:

我不确定你在做什么;但乍一看,您似乎正在尝试在 Web 环境中使用为 WinForms 应用程序编写的代码。这几乎肯定行不通,因为您的网络应用程序没有您需要的权限。
尝试查找如何在 Web 环境中执行此操作(因为您似乎正在处理配置文件,请尝试搜索 WEB.CONFIG 以开始)

【讨论】:

  • 这让我走上了解决我遇到的问题的正确轨道。我的 web.config 中缺少一些部分
【解决方案3】:

我尝试使用@shane 的答案,但最终使用 Hangfire 遇到了同样的异常。这段代码对我有用:

System.Configuration.Configuration configFile = null;
if (System.Web.HttpContext.Current != null)
{
    configFile =
        System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
    System.Configuration.ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = $"{System.AppDomain.CurrentDomain.BaseDirectory}Web.Config" };
    configFile = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
}

请注意,编辑 Web.config 会导致应用程序池重新启动

【讨论】:

  • 是的,这样打开 Web.config 不是一个好主意!一定有更好的办法
  • @JeremyRayBrown 在正在运行的应用程序中打开 Web.config 从来都不是一件好事。如果编辑了一个值,Web 应用程序将重新启动。这是最后的选择解决方案。
  • 我将代码调整为仅在启动时执行此操作。我的应用程序必须支持在运行时插入未知 dll 和 appSettings。但是,应用程序池只会回收一次,这是我能做到的。
猜你喜欢
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
  • 2014-09-03
  • 2018-10-31
  • 1970-01-01
相关资源
最近更新 更多