Access to path denied for files in WWWRoot folder

Anjali Agarwal 1,366 Reputation points
2023-02-07T18:26:06.8566667+00:00

I am trying to access two folders that resides inside wwwRoot. The folders are "BlankPDFFiles" and "FilledPDFFiles". I am trying to get the blank PDF files that resides inside BlankPDFFiles folder and write some data inside the file and then save it to the folder FilledPDFFiles. This is the structure of my solution:

User's image

when I am trying to access the blank PDF file, I am getting below error:

User's image

Below is my code:

public class PDFController : Controller

{

    private readonly IEmployeeService _employeeService;

    public readonly IConfiguration _configuration;

    public readonly ILogger _logger;

    private readonly IWebHostEnvironment _environment;

    public PDFController(IEmployeeService employeeService, IConfiguration configuration, ILogger<PDFController> logger, IWebHostEnvironment environment)

    {

        _employeeService = employeeService;

        _configuration = configuration;

        _logger = logger;

        _environment = environment;

    }

    public async Task<IActionResult> Index()

    {

      

        await PopulatePDFDoc();

        return View();

    }

public async Task PopulatePDFDoc()

    {

        AckPackage.Data.PDFPopulate.DocPDF doc = new Data.PDFPopulate.DocPDF();

        string pdfLic = _configuration["PDFLicense"].ToString();

        string filledPDF = Path.Combine(_environment.WebRootPath, "FilledPDFFiles");

        string blankPDF = Path.Combine(_environment.WebRootPath, "BlankPDFFiles");

        EmployeeInfo employee =  await _employeeService.GetEmployeeByEmployeeNumber(up.EmployeeId);

        await doc.popolatePDFDoc(pdfLic, filledPDF, blankPDF, employee);

    }

This is what I have in populatePDFDoc method:

public async Task popolatePDFDoc(string PDFLic, string filledPDF, string blankPDF, EmployeeInfo employee)

    {

        

        string pathToFile = filledPDF + "_Package"+ "_" + employee.EmployeeNumber;

        bool validLicense = BitMiracle.Docotic.LicenseManager.HasValidLicense;

       

        **using (PdfDocument pdf = new PdfDocument(blankPDF))**

        {

            foreach (PdfControl control in pdf.GetControls())

            {

                switch (control.Name)

                {

                    case "EmpID":

                        ((PdfTextBox)control).Text = employee.EmployeeNumber;

                        break;

                    case "Last Name":

                        ((PdfTextBox)control).Text = employee.LastName;

                        break;

                }

            }

            pdf.Save(pathToFile);

        }

I am getting an error at this line in popolatePDFDoc

using (PdfDocument pdf = new PdfDocument(blankPDF))

I am using third party vendor tool to populate PDF file. The entire application is an intranet application and behind a firewall so there is no security threat.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,131 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,239 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,179 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,006 Reputation points Microsoft Vendor
    2023-02-08T02:12:40.8133333+00:00

    Hi @Anjali Agarwal,

    For the access error, you can refer to my reply in this thread:

    For the web application, when host on IIS and remote server, we may be impersonating a user profile, running under a non-standard user account for the application pool (that is, not NETWORK SERVICE) or explicitly writing the file on a thread that’s running on a different user account. So, when access the folder, it might receive the Access to the path 'XXXX' is denied error.

    Looking at the user permissions for C: it’s clear that no special permissions have been granted for the web user. Thus, our task is first and foremost to identify the user that’s trying to write the file.

    You can try to use the Process Monitor to show real-time file system, Registry and process/thread activity, then you’ll be able to see the exact user account that tried to perform the denied action. After that you can granting it NTFS write rights to the C: directory.

    For example, I create a MVC application and use the following code to write text to a txt file,

        public IActionResult Privacy()  
        {  
            System.IO.File.WriteAllText(@"C:\Test.txt", "Hello world!");  
            return View();  
        }  
    

    After hosting the application on IIS, when calling the Privacy method, it will show the Access to the path 'C:\Test.txt' is denied error.

    Open the Process Monitor, enable the folder filter and click the cyan funnel icon to open up the filter editor window:

    258181-image.png

    
    

    Since we know IIS is running under the w3wp.exe process, we can add a filter that includes all events with a process name of w3wp.exe. As soon as we add an Include filter, all event that do not match an include filter are excluded.

    258151-image.png

    
    

    As we can see that, after hosting on IIS, when access the Test.txt file, the user is "IIS APPPOOL\website2".

    Then, we can go to the C drive properties window, and add the IIS APPPOOL\website2 user and granting it NTFS write rights to the C: directory

    258116-image.png

    
    

    And finally, we can run the website again and verify that we’ve now got proper permissions for writing the Test.txt file to the C: directory.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 26,181 Reputation points
    2023-02-07T18:40:26.82+00:00

    Try granting the application pool identity read/write access to the folders or run the application under an account that has access to the folders.

    Application Pool Identities