fass33443423
fass33443423

Reputation: 117

Azure path for readiing/writing static files

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) ?

Upvotes: 1

Views: 198

Answers (1)

Fei Han
Fei Han

Reputation: 27825

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");.

Upvotes: 1

Related Questions