【问题标题】:Azure path for readiing/writing static files用于读取/写入静态文件的 Azure 路径
【发布时间】:2020-06-10 05:56:29
【问题描述】:

我正在尝试在 Azure 中读/写一个文件,我将其放入 wwwroot\words.txt-文件夹

        private readonly string _Filename = @"wwwroot\words.txt";

System.IO.FileNotFoundException:找不到文件“D:\home\site\wwwroot\wwwroot\words.txt”。 文件名:'D:\home\site\wwwroot\wwwroot\words.txt'

  private readonly string _Filename = @"words.txt";

System.IO.FileNotFoundException:找不到文件“D:\home\site\wwwroot\words.txt”。 文件名:'D:\home\site\wwwroot\words.txt'

  private readonly string _Filename = @"D:\home\site\wwwroot\words.txt";

System.IO.FileNotFoundException:找不到文件“D:\home\site\wwwroot\words.txt”。 文件名:'D:\home\site\wwwroot\words.txt'

基于此post

private readonly string _Filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "words.txt");

System.IO.FileNotFoundException:找不到文件“D:\home\site\wwwroot\words.txt”。 文件名:'D:\home\site\wwwroot\words.txt'

在本地有效。有什么我想念的吗(不使用数据库)?

【问题讨论】:

标签: azure asp.net-core deployment


【解决方案1】:

我正在尝试在 Azure 中读/写一个文件,我将其放入 wwwroot\words.txt 文件夹

要达到你的要求,你可以试试下面的代码sn-p。

public class HomeController : Controller
{
    private IWebHostEnvironment _env;

    public HomeController(ILogger<HomeController> logger, IWebHostEnvironment env)
    {
        _logger = logger;
        _env = env;
    }
    public IActionResult ReadTxt()
    {
        var path = Path.Combine(_env.ContentRootPath, "words.txt");

        using (FileStream fs = System.IO.File.Create(path))
        {
            byte[] content = new UTF8Encoding(true).GetBytes("Hello World");

            fs.Write(content, 0, content.Length);
        }

        string text = System.IO.File.ReadAllText(path);

        ViewData["path"] = path;

        ViewData["mes"] = text;

        return View();
    }

查看页面

<h1>ReadTxt</h1>

Read file form @ViewData["path"]
<hr />
@ViewData["mes"]

测试结果

另外,如果words.txt存储在web root中,如下所示。

要访问它,您可以使用var path = Path.Combine(_env.WebRootPath, "words.txt");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 2013-02-14
    • 2015-03-02
    • 2018-02-10
    • 2015-06-07
    相关资源
    最近更新 更多