Access to the path is denied

Burjua picture Burjua · Feb 2, 2011 · Viewed 523.9k times · Source

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?

Answer

Hans Passant picture Hans Passant · Feb 2, 2011

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.