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:
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);
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].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With