access to the path is denied

It’s time for another post in our series about Debugging common .NET exceptions. Today, I want to introduce you to System.UnauthorizedAccessException . The exception is typically caused by an IO error, but other issues like security restrictions are also known to utilize this error. Let’s dig in!

Handling the error

Catching the exception is straightforward. Let’s create a small program to provoke and catch this error. Before writing code, I’ll create a text file named c: emp
eadonly.txt . Once created, right click the file, select Properties and enable the Read-only checkbox. This causes, surprise!, the file to be read-only. Now for the code:

As shown in the code, we simply catch the UnauthorizedAccessException and log it to the console.

Debugging the error

UnauthorizedAccessException contains no additional status or error code property so that you can figure out what is going on. The only indication is to look in the Message property, which in most cases looks similar to this:

So, why is access denied? We can start by excluding some scenarios I’ve seen people suggest as wrong answers on StackOverflow:

  1. If a file was not found on disk (this doesn’t throw the UnauthorizedAccessException ).
  2. If a file is currently locked by another program (this throws an IOException ).
  3. If a file is being blocked by Windows.
  4. Accessing a file in a non-existing directory (this throws a DirectoryNotFoundException ).

The following sections point out different causes of the exception.

Would your users appreciate fewer errors?

A read-only file

Probably the easiest thing to check when dealing with files, is to right click the file and check if the Read-only checkbox is checked:

Simply uncheck Read-only and try again.

If you want to, you can unlock a read-only file in C# and try again:

Current user doesn’t have access to a file

Another instance of the UnauthorizedAccessException is caused by issues with the user executing the program. If not running in elevated mode (Admin rights in Windows), the current user won’t have access to various Windows directories like c:Windows and c:Program Files . A simple fix for this error is to run the program as Administrator.

If the error is generated by a Windows Service, open Services, locate your service on the list and double-click it. On the Log On tab, make sure your service is configured with a user with access to the resource causing the exception. Services running as Network Service have very limited access to local resources. I would recommend you chat with your systems administrator to decide if you want to go with the default service users or create a custom one with custom permissions.

Access to file system from IIS

If you are experiencing this error while browsing a website hosted on IIS, it’s a similar error to the one described above. A .NET application hosted on IIS, uses the application pool user as a default to access files on the file system.

To fix this, add the IIS AppPool user to the root folder of your application by right clicking the folder and selecting Properties. Select the Security tab and add the IIS AppPool user:

Like Windows Services, you can also decide to create a custom user to access the file system from IIS. Create a new Windows (or AD) user and click your site inside the IIS Manager. From the Actions window click Basic Settings. Finally, click the Connect as button and input the new user below Specific user:

This example illustrates the scenario where the IIS user doesn’t have access to the folder containing the website files. You may also experience other scenarios where Windows authentication is used to control individual website users access to one or more files on the file system. In these cases, you want to re-use the example above to catch the exception in your code and inform the website user in a better way than showing an IIS error page.

Also make sure to read the other posts in this series: Debugging common .NET exception.

Восстановить работоспособность Trados Studio при возникновении ошибки Access to the path ‘F:System Volume Information’ is denied очень просто

Иногда Trados Studio при импорте пакета выводит загадочное сообщение:

При этом пакет не импортируется, проект в списке не появляется и работать невозможно. Причем папка System Volume Information действительно есть на диске, но она скрытая, и непонятно, какое отношение она имеет к проектам Trados Studio.

Из-за чего возникает такая ошибка, не вполне ясно, но метод ее устранения довольно прост:

  • Закрыть Trados Studio.
  • Удалить файл UserSettings.xml в папке Trados Studio. Обычно он находится в папке c:Users[USER NAME]AppDataRoamingSDLSDL Trados Studio[Trados Studio version].
  • Запустить Trados Studio.
  • Импортировать пакет повторно.

Этот метод работает в Trados Studio 2015 и 2017, но должен работать и в других версиях.

I know this question was asked many times here, but I can’t find a solution to my problem. I’m trying to save image to the folder in .net c# but get this exception:

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?

20 Answers 20

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.

Access to the path ‘C:inetpubwwwrootmysiteimagessavehere’ 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:inetpubwwwrootmysiteimagessaveheremumble.jpg’. Consider Path.Combine() to reliably generate the path name.

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:

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.

After doing this everything works as expected.

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.

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

Old Code

Working Code

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

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

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.

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:

MyNetworkServerc$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

MyNetworkServerSomeDirectoryOrOther

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

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

Оцените статью