Asp.Net HttpPostedFile.SaveAs fails: access is denied

716 Views Asked by At

In my ASP.NET web application, I am trying to upload a file using JQuery Ajax which in turn calls .ashx handler. Files should be saved to pdf folder which is created under the project's tree using:

Add --> New Folder

When deployed and tested, SaveAs fails with access is denied error.

All solutions on the internet suggest editing permissions on the folder. So on server, I granted Network Service user full control over pdf folder, and upload worked then... but the problem is that any subsequent deployement of the web application just removes those permissions on server and the problem returns, of course.

I gave full control to Network Service over Inetpub folder to overcome that problem, and that solved the case. But is it acceptable to do that?

It feels wrong, so please, what do you suggest to solve the problem instead of my workaround?

Code in handler is as following:

public void ProcessRequest(HttpContext context)
{
   try
   {
       if (context.Request.Files.Count > 0)
       {
           HttpPostedFile postedFile = context.Request.Files[0];

           string filePath = context.Server.MapPath("~/pdf");

           string fileName = Path.GetFileName(postedFile.FileName);
           postedFile.SaveAs( Path.Combine(filePath , fileName) );

           string json = new JavaScriptSerializer().Serialize(
                     new { name = fileName });

           context.Response.StatusCode = (int)HttpStatusCode.OK;
           context.Response.ContentType = "text/json";
           context.Response.Write(json);
           context.Response.End();
        }
   }
   catch (Exception e)
   {
            context.Response.ContentType = "text";
            context.Response.Write(e.Message);
            context.Response.End();
    }
 }

Thanks in advance

1

There are 1 best solutions below

3
On

Can you try give the permission to that folder IIS_USR with full control .It will work. We have to provide the IIS user not network service account.