[英]Hosted asp.net application 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)。
我的代碼中缺少什么? 我該如何閱讀這些目錄?
查找所有已部署的文件后,
您嘗試讀取文件。 可以在wwwroot
文件夾中讀取文件。 所以把你的模板移到那里。 要訪問wwwroot
文件夾,請使用作為 IWebHostEnvironment 注入的IWebHostEnvironment
中的WebRootPath
屬性
public class EmailTemplateGenerator
{
private IWebHostEnvironment _env;
public EmailTemplateGenerator(IWebHostEnvironment env)
{
_env = env;
}
public void GetEmailBody(string templateName)
{
var template = File.OpenRead(Path.Combine(_env.WebRootPath, $"EmailTemplate/{templateName}.html")
}
}
嘗試以下操作:
在 Visual Studio 中
如果您使用 Visual Studio 發布,請右鍵單擊“EmailTemplate”文件夾和 select“屬性”下的每個文件,並將“復制到 Output 目錄”的值設置為“始終復制”。 這將使 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.