Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to the path ... is denied during fileupload in .net

I am not able to upload file in .net c#. I am using the following code:

try
{
    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);
    foreach (var file in provider.Contents)
    {
         var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Resources");                    
         var dataStream = await file.ReadAsStreamAsync();
         FileStream fileStream = File.Create(mappedPath, (int)dataStream.Length);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent("Successful upload", Encoding.UTF8, "text/plain");
    response.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue(@"text/html");
    return response;
}
catch (Exception e)
{
     return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}

This happens on localhost. I have "Access to the path ... denied" error. I have tried to change security permissions for folder "Resources", but probably I do not know which group/username to add Full Control.

I have tried:

  1. choose computername and add NETWORK SERVICE - Full control
  2. choose computername and add IIS_IUSERS - Full control
  3. I have tried all above and also running IDE as administrator
like image 528
renathy Avatar asked Aug 20 '15 09:08

renathy


2 Answers

In your foreach loop you have:

foreach (var file in provider.Contents)
    {
         var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Resources");                    
         var dataStream = await file.ReadAsStreamAsync();
         FileStream fileStream = File.Create(mappedPath, (int)dataStream.Length);
    }

File.Create's first argument should be the path to a file, but your mappedPath is the path to a directory. You could do something like:

var filePath = Path.Combine(mappedPath, fileNameWithExtension);
FileStream fileStream = File.Create(filePath, (int)dataStream.Length);
like image 186
Saeb Amini Avatar answered Nov 16 '22 18:11

Saeb Amini


It does look like you're attempting to overwrite the directory with your mappedPath assignment, which may be the actual cause, and not permissions.

However, in terms of permissions, given that you're referencing IIS_IUSERS, it seems like you're working within IIS. Consider granting write permission to the identity that your process is running as; check the 'Identity' (IIS7+) setting under the 'Process Model' (Advanced Settings for the App Pool) - if it's ApplicationPoolIdentity, you'll need to add that identity into the permissions for the folder.

i.e., if your application pool is called my-app.com, the local user would be [iis apppool\my-app.com].

like image 2
kcamp Avatar answered Nov 16 '22 17:11

kcamp