首页 > 解决方案 > 托管的 asp.net 应用程序 DirectoryNotFoundException

问题描述

我有一个应用程序在我的本地服务器上运行。该应用程序在本地运行,没有任何错误。但是,当我在Heroku. 它产生的错误为:

DirectoryNotFoundException: Could not find a part of the path'/app/heroku_output/EmailTemplate/EmailConfirm.html'.

我一直在尝试使用以下代码读取文件:

private const string templatePath = @"EmailTemplate/{0}.html";

private string GetEmailBody(string templateName)
{
    var body = File.ReadAllText(string.Format(templatePath, templateName));
    return body;
}

EmailTemplate如图所示,文件夹在我的根目录下。

在此处输入图像描述

该文件夹也已上传到 Github 并在 Heroku 中正确托管。但是应用程序正在查看错误项目目录中的文件,即 (/app/heroku_output)。

我的代码中缺少什么?我该如何阅读这些目录?

查找所有已部署的文件后,

标签: c#asp.net-core-3.1

解决方案


尝试以下操作:

在 Visual Studio 中

如果您使用 Visual Studio 发布,请右键单击“EmailTemplate”文件夹下的每个文件并选择“属性”并将“复制到输出目录”的值设置为“始终复制”。这将使 Visual Studio 将这些文件发布到托管环境。如果您使用不同的应用程序发布文件,只需确保将“EmailTemplate”文件夹发布到托管环境。

在代码中

为了安全起见,请始终通过基本 URL 访问您的文件。下面给出示例。

//private const string templatePath = @"EmailTemplate/{0}.html";
private const string templatePath = @"EmailTemplate\\{0}.html";

private string GetEmailBody(string templateName)
{
    //var body = File.ReadAllText(string.Format(templatePath, templateName));
    string baseURL = AppDomain.CurrentDomain.BaseDirectory;
    var body = File.ReadAllText(string.Format(baseURL + "\\" + templatePath, templateName));
    return body;
}

推荐阅读