【问题标题】:Access file path from appsettings.json for docker linux从 docker linux 的 appsettings.json 访问文件路径
【发布时间】:2021-07-21 17:24:12
【问题描述】:

在我的 asp .net 核心 Web 应用程序中,我从 appsettings.json 访问一些文件路径。并在那里创建一个包含一些内容的新文件。以下是我的appsettings.json

{
  "root_privatekeylocation": "C:\\CARepository\\Root\\rootprivatekey.pem",
  "root_publickeylocation": "C:\\CARepository\\Root\\rootpublickey.pem",
  "crl_location": "C:\\CARepository\\CRL\\Crl.crl",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

这适用于 Windows,因为它会创建目录 CARepositoryRoot 和文件 rootprivatekey.pem。以下是创建这些的代码:

string pathFromConfig= Configuration["root_privatekeylocation"];
string privateKey = textWriter.ToString();
//if directory not exist then create
System.IO.FileInfo file = new System.IO.FileInfo(pathFromConfig);
file.Directory.Create(); // If the directory already exists, this method does nothing.
    
using StreamWriter f = new StreamWriter(pathFromConfig);
f.Write(privateKey); 

现在,我需要在 Linux 服务器上运行此应用程序。因此,我从 VS for Linux 向应用程序添加 docker 支持,创建一个 docker 映像并使用该映像运行 docker 容器。为此,我更改了appsettings.json,因为Linux 将没有C:\\

{
  "root_privatekeylocation": "~/CARepository/Root/rootprivatekey.pem",
  "root_publickeylocation": "~/CARepository/Root/rootpublickey.pem",
  "crl_location": "~/CARepository/CRL/Crl.crl",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

调用应用程序 API 在给定路径上创建文件,它返回输出但不创建文件 ~/CARepository/Root/rootprivatekey.pem,我也无法在任何地方找到 CARepository。似乎它没有创建这条路径。我签入了 docker 容器 CLI。有谁能够帮我? Linux docker还有其他文件路径格式还是我需要更改C#代码?

【问题讨论】:

    标签: c# linux docker file asp.net-core


    【解决方案1】:

    不要使用 ~ 来指定用户的主文件夹,使用 Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); 或选择其他 SpecialFolder 枚举之一。

    https://docs.microsoft.com/en-us/dotnet/api/system.environment.getfolderpath?view=net-5.0

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多