1

I am trying to read/write a file in Azure, which i put into the wwwroot\words.txt-folder

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

System.IO.FileNotFoundException: Could not find file 'D:\home\site\wwwroot\wwwroot\words.txt'. File name: 'D:\home\site\wwwroot\wwwroot\words.txt'

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

System.IO.FileNotFoundException: Could not find file 'D:\home\site\wwwroot\words.txt'. File name: 'D:\home\site\wwwroot\words.txt'

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

System.IO.FileNotFoundException: Could not find file 'D:\home\site\wwwroot\words.txt'. File name: 'D:\home\site\wwwroot\words.txt'

Based on this post

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

System.IO.FileNotFoundException: Could not find file 'D:\home\site\wwwroot\words.txt'. File name: 'D:\home\site\wwwroot\words.txt'

Locally it works. Is there anything I miss (,without using a dataabase) ?

  • 1
    Please refer to this [article](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1). – Joey Cai Jun 10 '20 at 06:39

1 Answers1

1

I am trying to read/write a file in Azure, which i put into the wwwroot\words.txt-folder

To achieve your requirement, you can try the following code snippet.

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();
    }

View page

<h1>ReadTxt</h1>

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

Test Result

enter image description here

Besides, if words.txt is stored in web root, as below.

enter image description here

To access it, you can use var path = Path.Combine(_env.WebRootPath, "words.txt");.

Fei Han
  • 26,415
  • 1
  • 30
  • 41