NetCore获取文件内容

1、注入IWebHostEnvironment
private IWebHostEnvironment _hostEnvironment;
public FormBaseController(IWebHostEnvironment hostEnvironment)
{
    _hostEnvironment = hostEnvironment;
}

 

2、读取根目录下文件内容(Templates/Index.html)

public async Task<IActionResult> GetFormPageFileName()
{
    IFileProvider fileProvider = this._hostEnvironment.ContentRootFileProvider;
    IFileInfo fileInfo = fileProvider.GetFileInfo("Templates/Index.html");

    string fileContent = null;
    using (StreamReader readSteam = new StreamReader(fileInfo.CreateReadStream()))
    {
        fileContent = await readSteam.ReadToEndAsync();
    }
    return View(fileContent);
}

 

posted @ 2024-01-24 15:44  microsoft-zhcn  阅读(30)  评论(0编辑  收藏  举报