【问题标题】:How to access a file from IIS web service hosted by ServiceHost如何从 ServiceHost 托管的 IIS Web 服务访问文件
【发布时间】:2016-10-28 10:37:36
【问题描述】:

在我的 IIS 应用程序中,我以这种方式打开位于 wwwroot 目录中的文件:

File.ReadAllText("ConfigFile.json");

IISExpress 尝试打开C:\Program Files (x86)\IIS Express\ConfigFile.json中的文件

我以为 wwwroot 目录是工作目录,但显然不是这样。

Log4net 日志文件是相对于工作目录写入的,配置管理器文件也是如此。所以我不明白为什么用 System.IO.File 打开文件我有C:\Program Files (x86)\IIS Express 作为工作目录。

该问题的最佳解决方案是什么?我想我不必触摸当前定义的工作目录。

【问题讨论】:

  • 只需使用Server.MapPath > File.ReadAllText(Server.MapPath("ConfigFile.json"))

标签: c# asp.net file wcf iis


【解决方案1】:

您需要将IHostingEnvironment 注入到您的类中才能访问ApplicationBasePath 属性值

假设IHostingEnvironment类型是env那么你可以使用

File.ReadAllText(env.WebRootPath + "/ConfigFile.json");

如果你有一个名为 Read 的函数,那么你可以使用

public void Read(IHostingEnvironment env)
{
   File.ReadAllText(env.WebRootPath + "/ConfigFile.json");
}

【讨论】:

  • 我读过 IHostingEnvironment 可以注入 asp.net 控制器,但我没有 asp.net 控制器,只有 WCF Web 服务。如何获取 IHostingEnvironment 实例?
【解决方案2】:

好的,在由 ServiceHost 类托管的 IIS WCF 服务中工作的解决方案是:

AppDomain.CurrentDomain.BaseDirectory + "/ConfigFile.json"

它提供了在我的 IIS Express 环境和已部署的 IIS 环境中有效的完整绝对路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    相关资源
    最近更新 更多