Access to the path is denied что делать
Перейти к содержимому

Access to the path is denied что делать

PowerShell: системное администрирование и программирование

Всё о PowerShell в Windows и на Linux. Системное администрирование Windows

Ошибка в PowerShell «New-Item: Access to the path ‘…’ is denied» (РЕШЕНО)

При работе с командлетами вносящими изменения в файловую систему (создание, изменение или удаление файлов и данных в них), может возникнуть ошибка

Пример команды, вызывающей данную ошибку:

Эту же самую ошибку могут вызвать командлеты:

  • Clear-Item
  • New-Item
  • Remove-Item
  • Rename-Item

В сообщении ошибки сказано, что доступ к указанному пути отклонён. Причиной является недостаток прав на запись, изменение, удаление файла, например, из-за того, что вы не можете записывать в выбранную папку.

Чтобы исправить эту ошибку, нужно запустить PowerShell с правами администратора. Как это сделать смотрите в статье «Как запустить PowerShell с правами администратора».

Быстрый способ запустить PowerShell с правами администратора прямо в командной строке:

Эта команда запустит версию PowerShell 5 или PowerShell 6 — в зависимости от того, что у вас установлено в системе по умолчанию. Чтобы запустить последнюю версию, которую вы установили вручную, то есть PowerShell 7, выполните команду:

Ошибка «Access to the path '…' is denied» на Linux

На Linux может возникнуть такая же ошибка при выполнении аналогичных команд:

Чтобы её исправить, запустите PowerShell с sudo:

В результате ошибка исчезнет и команды будут выполнять нужные вам действия:

Доступ к пути ‘c: \ inetpub \ wwwroot \ myapp \ App_Data’ запрещен

Когда я пытаюсь запустить приложение, я получаю сообщение об ошибке:

Access to the path ‘c:\inetpub\wwwroot\myapp\App_Data’ is denied. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.UnauthorizedAccessException: Access to the path ‘c:\inetpub\wwwroot\myapp\App_Data’ is denied.

ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically \ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.

To grant ASP.NET access to a file, right-click the file in Explorer, choose «Properties» and select the Security tab. Click «Add» to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

Source Error:

Line 70: Protected Sub cmbSettingFiles_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbSettingFiles.SelectedIndexChanged
Line 71: Dim doc As XmlDocument = New XmlDocument()
Line 72: doc.Load(Path.Combine(basePath, cmbSettingFiles.SelectedValue)) Line 74: Dim settingsNode As XmlNode = doc.SelectSingleNode(«/settings»)

Source File: C:\myapp\install\install.aspx.vb Line: 72

Я попытался получить разрешение, сделав следующее:

To grant ASP.NET access to a file, right-click the file in Explorer, choose «Properties» and select the Security tab. Click «Add» to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

Но ошибка сохраняется.

Это как-то связано с моим кодом?

Как я могу это решить?

РЕДАКТИРОВАТЬ

Я решил проблему на своем компьютере разработчика, но я все еще получаю сообщение об ошибке на своем веб-сервере.

Debugging System.UnauthorizedAccessException (often followed by: 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!

Debugging System.UnauthorizedAccessException

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:\temp\readonly.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:

File propertiesFile properties

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 an 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\<AppPoolName> user:

Select Users or GroupsSelect Users or Groups

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:

Connect AsConnect As

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.

Добавить комментарий

Ваш адрес email не будет опубликован.