0
votes

I have an ASP.NET Core API app which runs some background processes via HangFire. One of the process includes writing a csv file onto the wwwroot folder as following:

public async Task Work(PerformContext context)
        {
            var latestLikes = await this.likeRepository
                .All()
                .Select(l => new LatestLikesServiceModel
                {
                    UserId = l.UserId,
                    BeatId = l.BeatId,
                })
                .ToListAsync();

            var modelPath = this.webHostEnvironment.ContentRootPath + "\\dataModel.csv";
            using (var writer = new StreamWriter(modelPath))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                csv.WriteRecords(latestLikes);
            }
        }

In localhost it works perfectly, but when I deploy it in azure the HangFire log returns: "System.UnauthorizedAccessException","ExceptionMessage":"Access to the path 'C:\home\site\wwwroot\dataModel.csv' is denied."
How can I resolve this issue?

2
'C' maybe denied, is it in the DIsk D?1_1
@BowmanZhu it is in the 'C:\'Georgi Popov
Is your function app based on window os or linux os?1_1
@BowmanZhu It is an app service based on windowsGeorgi Popov
D:\home\site\wwwroot\dataModel.csv.Jason Pan

2 Answers

0
votes

Below code works fine on my side:

using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace FunctionApp97
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ExecutionContext ec,
            ILogger log)
        {
            string str = ec.FunctionAppDirectory;
            log.LogInformation(str);
            using (var reader = new StreamReader(str+ @"\filename.txt"))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    log.LogInformation(line);
                }
            }
            return new OkObjectResult(str);
        }
    }
}
0
votes

After one week of researching I finally found out the solution
I should have mentioned that I use Azure DevOps for CI & CD.
By default the azure app service is deployed as a zip (which cuts the direct access to the file system) What I had to do was to change the Deployment method to a Web Deploy (Additional Deployment Options) and I finally have access to the file system. For more descriptive information, please refer:
https://tomasherceg.com/blog/post/azure-app-service-cannot-create-directories-and-write-to-filesystem-when-deployed-using-azure-devops#comments