210

I'm trying to save an image to a folder in .NET C# but I get this exception:

Access to the path 'C:\inetpub\wwwroot\mysite\images\savehere' is denied.The error occured at mscorlib because    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)

I gave full control to this folder (savehere) to network service and iis_iusrs, even gave full control to everyone but still getting this exception. I tried to give access via explorer and via IIS manager, still no luck

I'm doing it on Windows server 2008 R2 and IIS 7.5, Who do I need to give access?

2
  • Have you tried using a path relative to your application? I don't know much about Windows server, but it may be that it doesn't allow access to a `C:` root path.
    – Michael K
    Feb 2, 2011 at 17:47
  • 2
    Future readers: Check permissions on the file.
    – Ruskin
    Jan 12, 2015 at 14:22

27 Answers 27

289

Access to the path 'C:\inetpub\wwwroot\mysite\images\savehere' is denied

Read the message carefully. You are trying to save to a file that has the same name as the directory. That cannot work, you can't overwrite a directory filled with files with a single new file. That would cause undiagnosable data loss, "Access to the path is denied" is the file system fighting back to prevent that from happening.

The exception message is not ideal, but it comes straight from the OS and they are cast in stone. The framework often adds extra checks to generate better messages, but this is an expensive test on a network. Perf is a feature too.

You need to use a name like 'C:\inetpub\wwwroot\mysite\images\savehere\mumble.jpg'. Consider Path.Combine() to reliably generate the path name.

8
  • 28
    @Hans Passant Thanks for your, a bit harsh, statement. That made me look into my code realise I had made the same error.
    – LosManos
    Jul 18, 2011 at 20:15
  • for me, the problem was that the file was existing and the user could nout replace it
    – VinnyG
    Apr 3, 2012 at 15:29
  • 2
    Hah! I did the exact same thing. Apr 9, 2013 at 19:37
  • Maybe this thread should be locked to protect against "Me too!" answers. Because me too! In my case I should add that I am annoyed that an HttpPostedFileBase object's SaveAs method required a name in addition to the path, considering the name is another property on the object. Of course I guess you could give it a different name this way.
    – Ralph
    Feb 8, 2016 at 20:19
  • 1
    I got this error while trying to write a file in a unit test (nothing to do with IIS or anything web-related), and the error message is so vague. Why doesn't it say something among the lines of "Cannot open \path\to\file as a file"?
    – MarioDS
    Aug 23, 2016 at 14:29
103

You need to find out from the application pool for the website what is the identity it is running under (by default this is Application Pool Identity) and grant that the correct permissions.

12
  • Ok, thanks, I have 5 pools, they all have identity as ApplicationPoolIdentity , how do I give permissions to it?
    – Burjua
    Feb 2, 2011 at 17:40
  • 22
    @Burjua - look for the IIS APPPOOL\DefaultAppPool user. See this article on the official IIS site: learn.iis.net/page.aspx/624/application-pool-identities
    – Oded
    Feb 2, 2011 at 17:46
  • 1
    Ok, as written in this article I added DefaultAppPool and gave full control permissions to it, but still getting the same error
    – Burjua
    Feb 2, 2011 at 18:14
  • 2
    I know I am too late. But I am facing the same problem. The OP had clearly mentioned that he had given everyone the Full control. If we grant everyone the Full control, even then we need to grant access to DefaultAppPool? It's confusing.
    – qurban
    May 2, 2015 at 12:28
  • 3
    @stom - of course it isn't best practice. You are opening the website to all kinds of vulnerabilities. You just want read/write permissions to the Images directory for the user/identity that is running the website (you will need to ask your host provider about that).
    – Oded
    Nov 21, 2015 at 9:39
26

I was having the same problem while trying to create a file on the server (actually a file that is a copy from a template).

Here's the complete error message:

{ERROR} 08/07/2012 22:15:58 - System.UnauthorizedAccessException: Access to the path 'C:\inetpub\wwwroot\SAvE\Templates\Cover.pdf' is denied.

I added a new folder called Templates inside the IIS app folder. One very important thing in my case is that I needed to give the Write (Gravar) permission for the IUSR user on that folder. You may also need to give Network Service and ASP.NET v$.# the same Write permission.

enter image description here

After doing this everything works as expected.

0
18

I had exactly the same problem.

The solution was that the file I was trying to access was readonly, as it was copied from a template file that was readonly.

<facepalm />

3
  • The Altova AltovaXML Application Class (DCOM) is doing this. Caused me problems.
    – Mike D
    Feb 21, 2014 at 11:48
  • By which I mean, it must be using something similar to the following line, meaning XSLT must not be readonly. 'FileStream ms = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);'
    – Mike D
    Feb 21, 2014 at 15:15
  • 1
    Here's a <facepalm /> from me as well. Oh and.. Thanks, readonly was my problem also. Feb 14, 2017 at 8:25
14

I got this problem when I try to save the file without set the file name.

Old Code

File.WriteAllBytes(@"E:\Folder", Convert.FromBase64String(Base64String));

Working Code

File.WriteAllBytes(@"E:\Folder\"+ fileName, Convert.FromBase64String(Base64String));
1
  • This worked for me, but note that if the file does not exist this will throw an exception instead of creating a new one. So I suggest that you check first if the file exists (you need to overwrite), then use the working code otherwise (you need to create) use the old code.
    – Zeyad
    Oct 8, 2022 at 10:32
11

My problem was that I had to ask for Read access only:

FileStream fs = new FileStream(name, FileMode.Open, FileAccess.Read);
1
  • 1
    Bingo - this one bit me, too! Thank you for the post!
    – paulsm4
    Jun 11, 2020 at 16:21
6

please add IIS_IUSERS full control permission to your folder. you find this option from security tab in folder properties. find this option and user in this image

2
  • Bad advice. Arbitrarily giving IIS_USERS "full control" - without careful consideration - is the moral equivalent of saying "Nurse - chainsaw" ;)
    – paulsm4
    Jun 11, 2020 at 16:38
  • I add the Modify Permission and it works Jul 31 at 19:45
6

In my case, I'm trying to access a file that is set to be read-only

enter image description here

And I solved it by disabling read-only and I got it fixed!

enter image description here

Hope it can be helpful for someone experiencing a situation like me.

4

What Identity is your Application Pool for the Web application running as, to troubleshoot, try creating a new App Pool with say Network Service as its identity and make your web application use that new App Pool you created and see if the error persists.

4

The following tip isn't an answer to this thread's original question, but might help some other users who end up on this webpage, after making the same stupid mistake I just did...

I was attempting to get an ASP.Net FileUpload control to upload it's file to a network address which contained a "hidden share", namely:

\MyNetworkServer\c$\SomeDirectoryOrOther

I didn't understand it. If I ran the webpage in Debug mode in Visual Studio, it'd work fine. But when the project was deployed, and was running via an Application Pool user, it refused to find this network directory.

I had checked which user my IIS site was running under, gave this user full permissions to this directory on the "MyNetworkServer" server, etc etc, but nothing worked.

The reason (of course!) is that only Administrators are able to "see" these hidden drive shares.

My solution was simply to create a "normal" share to

\MyNetworkServer\SomeDirectoryOrOther

and this got rid of the "Access to the path... is denied" error. The FileUpload was able to successfully run the command

fileUpload.SaveAs(networkFilename);

Hope this helps some other users who make the same mistake I did !

Note also that if you're uploading large files (over 4Mb), then IIS7 requires that you modify the web.config file in two places. Click on this link to read what you need to do: Uploading large files in ASP.Net

4

I Solved with this setting:

IIS > Application Pools > [your site] > Advanced Settings... > Identity > Built-in accound > LocalSystem

5
  • 3
    This is giving your Website LocalAdmin permissions. This is a security concern.
    – Rich-Lang
    Apr 10, 2019 at 13:49
  • 2
    DO NOT EVER run your website under LocalSystem account. EVER. PERIOD. Jul 7, 2019 at 13:51
  • @MihailShishkov why? Jul 8, 2019 at 20:21
  • 4
    @MohammadHosseinGanjyar LocalSystem has admin rights over the system. By running the website under that account you basically give it the keys to the entire system and probably the entire local network on which the server resides. This means that if an attacker finds a way to exploit your website - the website and the entire system are screwed. That's the reason privileges/rights and accounts exist in the first place. As a rule of a thumb remember this - no software should run with greater privileges then it needs to do its job. For example blog site does not need the right to format D:drive Jul 10, 2019 at 4:24
  • This answer is recommending that a security flaw be introduced and should be deleted.
    – Ruzihm
    Nov 22, 2021 at 22:43
2

My problem was something like that:

FileStream ms = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);

but instead of using path I should use File.FullName... I don't know if it's going to help anyone else, just passing my own experience with this erro given!

2
  1. Change the setting from built-in account to custom account and enter the other server's username and password.

  2. Keep the setting as integrated (instead of classic mode).

1

If you get this error while uploading files in Sub domain And working correct in your localhost, then follow below steps:

Solution:

Plesk Panel

  • Login to your Plesk Panel. Select Your Sub domain which is giving error.
  • Click on Hosting settings.
  • Select Additional write/modify permissions and Apply.

CPanel

  • I am not sure about options available in CPanel. But IF you give permission to directory (In CPanel it has to be decimal number like 777, 755) will resolve the error.

For more details refer here

Reason for Error:

  • Let's Assume FileUpload.SaveAs(Server.MapPath("~/uploads/" + *YOUR_FILENAME*)) will be your code to move your files to upload path.
  • Server.MapPath will give you physical path (Real Path) of directory. But your Sub domain may don't have permission for access physical path.

  • So, If you give permission for sub domain to access write/modify permission, it will resolve the issue.

1

you need to add access parameter with ReadWrite value as following

using (var stream = new FileStream(localPath, FileMode.Create, access : FileAccess.ReadWrite))
{
    file.CopyTo(stream);
} 
0
0

Make Directory savehere to be virtual directory and give read/write permission from control panel

1
  • Run InetMgr.exe then go to your folder savehere under mysite (web application/web site in IIS) it will be on left hand side where DefaultApp is located, i hope u got i am telling
    – Harsh Baid
    Feb 2, 2011 at 18:19
0

Had a directory by the same name as the file i was trying to write, so people can look out for that as well.

0

I encountered this problem while developing on my local workstation.

After several unsuccessful iisreset invocations, I remedied this situation by rebooting my machine.

In retrospect, an open file handle may have been causing issues.

0

In my case I had to add a .NET Authorization Rule for the web site in IIS.

I added a rule to allow anonymous users.

.NET Authorization Rules

0

I had the same problem but I fixed it by saving the file in a different location and then copying the file and pasting it in the location where I wanted it to be. I used the option to replace the the existing file and that did the trick for me. I know this is not the most efficient way but it works and takes less than 15 seconds.

0

Maybe it'il help you.

string tempDirectoryPath = @"C:\Users\HOPE\Desktop\Test Folder";
string zipFilePath = @"C:\Users\HOPE\Desktop\7za920.zip";
Directory.CreateDirectory(tempDirectoryPath);
ZipFile.ExtractToDirectory(zipFilePath, tempDirectoryPath);
0

I had a lot of trouble with this, specifically related to my code running locally but when I needed to run it on IIS it was throwing this error. I found that adding a check to my code and letting the application create the folder on the first run fixed the issue without having to mess with the folders authorizations.

something like this before you call your method that uses the folder

bool exists = System.IO.Directory.Exists("mypath");

        if (!exists)
            System.IO.Directory.CreateDirectory("mypath");
0

You can try to check if your web properties for the project didn't switch to IIS Express and change it back to IIS Local

0

Make sure you that your target in System.IO.Delete(string file) is a file which is existed. Maybe there is a mistake in your code ;Like you don't pass the correct file name to the method , or your target is a folder. In these cases you'll see the : "access to the path is denied error".

0

I recently encountered the problem while trying to access a file that was passed through command-line parameters into my .Net Core application, It happened due to the fact that when the application is run under a "Open with" (System explorer context menu under a file) system menu, the currently active user may vary, and the user didn't have the access right to my external drive that I was trying to open a file from.

It took me like 3-4 hours to understand and I solved it by setting the security settings for the folder that contained the file. For Windows 10 x64 : Just use Properties -> Security -> Users and Groups -> Change.. -> Add -> Additional -> Search -> <your windows account name> -> OK -> OK -> Set full access for your current account. Also make sure that the file is "unblocked" in properties.

0

For me it was different, the Windows security didn't let delete or move folders and files so it return dined error.

windows Security -> Virus & threat protection -> Add an exclusion.(process or, ....)

-1

I created a virtual dir with full permission and added the ffmpeg source and video files there, so finally it made sense as it can be acess by anyone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.