s

asp.net mvc web api using server.mappath to resolve the error access to the path is denied edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 26 September 2020 | 3314

In this post, we will see how to use asp.net MVC Server.MapPath() and Asp .net web API Hosting.HostingEnvironment.MapPath() function to store the file in the right folder. Server.MapPath() function takes one parameter The virtual path in the Web application and returns a string The physical file path on the Web server that corresponds to the path.

Problem Statement

In my asp .net MVC application if I try to write a file with the code below I will get an error

public class HomeController : Controller
{
    public ActionResult Index()
    {
        System.IO.File.WriteAllText("demo.txt", "hello world this is a test");
        return View();
     }
}


An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll but was not handled in user code

Access to the path 'C:\\Program Files (x86)\\IIS Express\\demo.txt' is denied

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.UnauthorizedAccessException: Access to the path 'C:\Program Files (x86)\IIS Express\demo.txt' is denied.

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

Solution: Asp .Net MVC Application

modify the code to get the physical path of the file.

String filename = Server.MapPath("/demo.txt");
System.IO.File.WriteAllText(filename, "hello world this is a test");

when you run the application you can see that the file will be written to the Application root folder.

Solution: Asp .Net MVC Web Api Application

For an asp .net MVC web API application, you have to use the System.Web.Hosting.HostingEnvironment.MapPath method from System.Web.Hosting.HostingEnvironment namespace.

public IHttpActionResult Index()
{
    String filename = System.Web.Hosting.HostingEnvironment.MapPath("/demo.txt");
    System.IO.File.WriteAllText(filename, "hello world this is a test");
    return Ok();
}