C# 不在独立exe中运行时,必须指定exePath

C# 不在独立exe中运行时,必须指定exePath,c#,web-config,app-config,C#,Web Config,App Config,当我使用web应用程序时,下面的代码行 Configuration objConfig = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); 类库中出现以下错误: “不在独立exe中运行时,必须指定exePath。” 以前使用的是控制台应用程序,代码可以访问app.config。我尝试在类库中使用System.Web.Configuration,但在.Net选项卡中没有“添加引用”的dll

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

Configuration objConfig = 
    ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None);
类库中出现以下错误:

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

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


请帮忙:)

我不知道你在做什么;但乍一看,您似乎在尝试在web环境中使用为WinForms应用程序编写的代码。这几乎肯定行不通,因为您的web应用程序没有您需要的权限。

尝试在web环境中查找如何执行此操作(因为您似乎正在处理配置文件,请尝试在web.config上搜索以开始)

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

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

我试着使用@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将导致应用程序池重新启动

您使用的是什么版本的.NET Framework?@wgraham web应用程序在.NET 4.0中,类库在3.5中。这是一个类库,您有源代码,还是第三方库?这让我走上了解决问题的正确道路。我在我的网站上遗漏了一些部分。我相信“~”应该是“~/”(“~”对我不起作用)我真不敢相信这是如此糟糕。我绝对不想引用我正在执行此操作的System.Web。有些情况下,
HttpContent
为空,但您仍然需要调用
WebConfiguration Manager
,例如实际在单独线程中运行的任务,例如,
HostingEnvironment.QueueBackgroundWorkItem
是,像那样打开Web.config不是一个好主意!一定有更好的办法way@JeremyRayBrown在正在运行的应用程序中打开Web.config永远都不好。如果编辑了值,web应用程序将重新启动。这是最后一个选项解决方案。我将代码调整为仅在启动时执行此操作。我的应用程序必须支持在运行时插入未知DLL和appSettings。但是,应用程序池只能回收一次,这是我所能做的最好的。