You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure App Service Linux环境下C#无法读取JSON文件,求解决方法

解决Azure App Service Linux计划下C#读取JSON文件的问题

原来依赖Assembly.GetEntryAssembly().Location获取路径的方式在Linux环境下失效,核心原因是Azure App Service Linux计划的部署结构、程序集存放路径和Windows计划存在差异。以下是几种可靠的替代方案:

方案1:利用ASP.NET Core的内容根路径(适用于Web项目)

ASP.NET Core提供了IWebHostEnvironment服务,可直接获取项目的内容根目录(即项目文件部署后的根路径):

  1. 先在类中注入IWebHostEnvironment:
private readonly IWebHostEnvironment _webHostEnv;

public YourServiceOrController(IWebHostEnvironment webHostEnv)
{
    _webHostEnv = webHostEnv;
}
  1. 拼接路径并读取文件:
string jsonFilePath = Path.Combine(_webHostEnv.ContentRootPath, "file.json");
string jsonData = File.ReadAllText(jsonFilePath);

方案2:将JSON文件设为嵌入式资源(跨平台通用)

把JSON文件嵌入到程序集中,彻底摆脱对文件系统路径的依赖:

  1. 右键项目中的JSON文件 → 属性 → 「生成操作」选择「嵌入的资源」,「复制到输出目录」选择「不复制」。

  2. 通过程序集读取嵌入式资源:

var currentAssembly = Assembly.GetExecutingAssembly();
// 资源名称格式:项目命名空间 + 文件路径(比如文件在根目录就是「YourProjectName.file.json」)
string resourceFullName = "YourProjectNamespace.file.json";

using var resourceStream = currentAssembly.GetManifestResourceStream(resourceFullName);
using var streamReader = new StreamReader(resourceStream);
string jsonData = streamReader.ReadToEnd();

方案3:基于应用基目录读取(适用于控制台/非Web项目)

使用AppContext.BaseDirectory获取应用的基目录,同时确保文件被正确部署:

  1. 右键JSON文件 → 属性 → 「复制到输出目录」选择「始终复制」或「如果较新则复制」,确保部署时文件会同步到输出目录。

  2. 读取文件:

string appBaseDir = AppContext.BaseDirectory;
string jsonFilePath = Path.Combine(appBaseDir, "file.json");
string jsonData = File.ReadAllText(jsonFilePath);

注意事项

  • 避免手动拼接路径(比如path+"/"+"file.json"),改用Path.Combine,它会自动适配Windows/Linux的路径分隔符。
  • 若使用方案1/3,需确认Azure App Service部署时,JSON文件已被包含在部署包中(可通过Kudu工具查看Linux容器内的文件结构验证)。

内容的提问来源于stack exchange,提问作者Mandar Jogalekar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 16:25:02