Error unc path too long

Слишком длинный целевой путь: Имена файлов слишком длинны для помещения в эту целевую папку. Попробуйте использовать более короткое имя имя файла или расположение

Обновлено 28.11.2020

Длинные пути Windows

Добрый день! Уважаемые читатели и гости одного из крупнейших IT блогов Pyatilistnik.org. В прошлый раз мы с вами разобрали возможности утилиты PING, рассмотрели как ее применять на практике. В сегодняшней публикации я вам покажу, как устраняется боль и печаль в операционных системах Windows, я говорю про длинные пути, в своей практике я очень часто встречал жалобы «Слишком длинный целевой путь» или «Слишком длинный конечный путь«, то же самое вы можете встретить и при удалении. Ниже я покажу, как выкручиваться из данной ситуации.

Описание проблемы длинных путей

Раньше имена файлов в Windows ограничивались форматом 8.3 — всего восемь символов для имени файла и три для расширения. С появлением Windows 95 Microsoft сняла этот предел и позволила использовать гораздо более длинные имена.

Тем не менее, файловая система Windows по-прежнему накладывает некоторые ограничения, например, какие символы могут использоваться в именах файлов и общую длину путей. Некоторое время максимальная длина пути составляла 260 символов, но с появлением Windows 10, часть ограничений начала потихоньку уходить, например для приложений и появилась возможность отключить проверку MAX_PATH и использовать длинные пути без префикса \?.

Что интересно, значение в 260 символов обусловлено значением MAX_PATH Win32 API. У файловой системы NTFS максимальная длина пути ″немного″ больше и составляет  32767 символа. Для обхода ограничений Win32 API некоторые приложения используют формат UNC, указывая абсолютный путь с префиксом \?, например так:

\?C:директорияподдиректорияимя файла

Хочу отметить, что на период ноября 2020 года и последней версий Windows 10 1909, в ПРОВОДНИКЕ Windows до сих пор есть ограничения в 260 символов, и мы все слышим обещания, что их исправят

Большинство людей может и не столкнуться с ней, а вот почти каждый системный администратор обязательно это увидит. Тут все дело в том, что в большинстве организаций есть свои сетевые файловые ресурсы, через которые пользователи производят обмен и работу с документами. В какой-то момент люди могут создать такой путь, который будет 258 или 260 символов, попытаются туда скопировать файл, а им выдастся ошибка:

Слишком длинный целевой путь: Имена файлов слишком длинны для помещения в эту целевую папку. Попробуйте использовать более короткое имя имя файла или расположение с более коротким путем

Имена файлов слишком длинны для помещения в эту целевую папку. Попробуйте использовать более короткое имя имя файла или расположение с более коротким путем

Тоже самое при копировании в папку, так же выскакивает «Слишком длинный целевой путь».

Слишком длинный целевой путь, решаем за минуту

Вот ошибка при извлечении архива в сетевую папку:

Не удается завершить извлечение. Слишком длинный конечный путь. Переименуйте сжатую ZIP-папку и повторите попытку

Не удается завершить извлечение. Слишком длинный конечный путь. Переименуйте сжатую ZIP-папку и повторите попытку

Методы снимающие ограничения на длину пути в Windows

  • Через групповую или локальную политику Windows (Применимо только к Windows 10 и Windows Server 2016 и выше)
  • Через реестр Windows (Применимо только к Windows 10 и Windows Server 2016 и выше)
  • Через сторонние утилиты 7-Zip, Far, TotalCommander (Применимо ко всем версиям Windows)
  • Использование силинков (символических ссылок) (Применимо ко всем версиям Windows)
  • Через сетевой диск, для укорачивания пути
  • Утилиты xcopy, robocopy

Нюансы длинных путей в приложениях

Есть один нюанс. Этот новый параметр (имеется ввиду та политика и ключ реестра) не обязательно будет работать со всеми существующими приложениями, но он будет работать с большинством. В частности, любые современные приложения должны работать нормально, как и все 64-битные приложения. Старые 32-разрядные приложения должны быть применимы для работы, что на самом деле просто означает, что разработчик указал в файле манифеста приложения, что приложение поддерживает более длинные пути. Большинство популярных 32-битных приложений не должно вызывать проблем. Тем не менее, вы ничем не рискуете, пробуя настройку. Если приложение не работает, единственное, что произойдет, это то, что оно не сможет открывать или сохранять файлы, сохраненные в местах, где полный путь превышает 260 символов.

Если вы разработчик, то чтобы ваше приложение имело возможность работать с длинными путями Windows, в манифесте обязательно указывайте следующие настройки:

<application xmlns=»urn:schemas-microsoft-com:asm.v3″>
<windowsSettings>
<longPathAware xmlns=»http://schemas.microsoft.com/SMI/2016/WindowsSettings»>true</longPathAware>
</windowsSettings>
</application>

Как в Windows 10 отключить ограничение на длину пути в 260 символов через политику

Чем примечателен данный метод, так это тем, что неподготовленных пользователей он не вынуждает выполнять команды или производить правку реестра, тут все в графическом виде. Так же если у вас есть домен Active Directory и вы хотите массово убрать ошибки «Слишком длинный целевой путь» или «Слишком длинный конечный путь» в приложениях и запретить им проверять MAX_PATH и использовать длинные пути без префикса \?, то групповые политики вам это помогут.

Еще раз напоминаю, что данный метод подойдет и для серверных версий, даже самых современных Windows Server 2019

Покажу для начала, как делать через локальную политику, открываете окно «Выполнить» в котором пишите gpedit.msc.

Хочу отметить, что для Windows 10 Home данный метод работать не будет, там просто нет редактора локальных политик, там придется лезть в реестр Windows

Как в Windows 10 отключить ограничение на длину пути в 260 символов

Далее идем по пути:

Конфигурация компьютера — Административные шаблоны — Система — Файловая система (Computer configuration — Administrative templates — System — Filesystem)

Найдите тут параметр «Включить длинные пути Win32 (Enable Win32 long paths)«, по умолчанию он отключен, и я честно не понимаю почему. Активируйте его.

Включить длинные пути Win32

То же самое вы можете сделать централизовано для массового управления через групповые политики, все ветки те же самые.

Как я писал выше, в проводнике это не даст ни каких эффектов, поэтому вы все так же будите получать ошибку при копировании, создании, удалении «Слишком длинный целевой путь» или «Слишком длинный конечный путь«. Ниже я покажу, что делать если нужно что-то там удалить или изменить. Данное ограничение в длине пути теперь не подхватиться на лету всеми приложениями, потребуется перезагрузка.

Включение поддержки длинных путей через реестр

Данный метод ни чуть не сложнее предыдущего и делает все то же самое, включает поддержку длинных путей свыше 256 символов для приложений Windows. Когда вы что-то меняете через редактор политик, по сути меняются настройки в реестре, это нужно помнить и знать. Сейчас я вам покажу какой ключ меняется. Откройте редактор реестра Windows.  Перейдите в раздел:

HKLMSystemCurrentControlSetControlFileSystem

тут вам необходимо найти параметр LongPathEnabled, которому для активации поддержки длинных путей и изменения ограничений в MAX_PATH, нужно задать значение «1». Тут потребуется перезагрузка.

Включение поддержки длинных путей через реестр Windows. LongPathEnabled

Все что вам нужно, это распаковать zip-архив и запустить нужный файл активации, потом так же перезагрузиться, так как у вас будет создан нужный ключ реестра, без необходимости лезть в реестр самостоятельно.

Ключи реестра для активации MAX_PATH

Еще вы можете сделать такую поддержку и для конкретного пользователя по пути:

HKEY_CURRENT_USERSOFTWAREMicrosoftWindows CurrentVersionGroup Policy Objects {48981759-12F2-42A6-A048-028B3973495F} MachineSystemCurrentControlSetPolicies

Если там нет ключа LongPathsEnabled, то создайте его, тип DWORD (32 бита) и значение 1.

Как в Windows 10 отключить ограничение на длину пути в 260 символов через PowerShell

Не все люди готовы копаться в редакторах и реестрах, им нужно быстрое решение, одним из таких является PowerShell. В оболочке выполните команду для активации параметра «Включить длинные пути Win32 (LongPathEnabled)». Не забываем перезагрузить систему.

Set-ItemProperty -Path HKLM:SYSTEMCurrentControlSetControlFileSystem -Name LongPathsEnabled -Value 1

Как в Windows 10 отключить ограничение на длину пути в 260 символов через PowerShell

Как удалять, копировать, переносить файлы и папки при ошибке с длинными путями

Разобравшись с тем, как отключить проверку MAX_PATH в приложениях, давайте теперь поймем и научимся решать проблему длинных путей на файловых шарах и просто в проводнике. Классическая ситуация, когда пользователь попытался перенести свой файл или удалить его, создать папку и так далее, и он получает ошибку с пресловутыми длинными путями. Он просит разобраться вас и тут начинаются танцы с бубнами, вы просите его либо переименовать часть пути, или попросить его произвести действия в другом расположении, или просто забить, сказав, что виновата Windows со своими ограничениями, но мы же с вами профессионалы и инженеры, поэтому должны уметь выходить из таких ситуаций.

Как в Windows 10 отключить ограничение на длину пути в 260 символов через командную строку

Запустите командную строку в режиме администратора и введите:

reg add «HKLMSYSTEMCurrentControlSetControlFileSystem» /v LongPathsEnabled /t REG_DWORD /d 1

Потребуется перезагрузка.

Как в Windows 10 отключить ограничение на длину пути в 260 символов через командную строку

Обход ограничений длинных путей через 7zFM

Наверняка многие знают архиватор 7Zip, но мало кто пользуется его файловым менеджером 7zFM.exe, а зря именно он может вам помочь в ситуации с сообщением «Слишком длинный целевой путь» или «Слишком длинный конечный путь».  Вот у меня есть тестовая директория, у которой уже есть 260 символов в пути, и я не могу там создавать новую папку.

Исправляем Слишком длинный путь к источнику через 7zFM

Откройте 7zFM.exe и перейдите в нем в конечную папку вашего пути.

Для создания новой папки нажмите клавишу F7.

Создание папки в 7zFM.exe

Задайте необходимое вам имя, в моем примере это будет «БОльше 260 Microsot«.

Указание имени у создаваемой папки в 7zFM.exe

В результате у нас создалась новая папка и заметьте 7zFM не ругнулся на наличие длинных путей, он их игнорирует просто и все.

Успешно созданная папка через 7zFM.exe

Проверяем, что директория доступна через проводник Windows.

Обход ограничений длинных путей через 7zFM

Все прекрасно отображается. Теперь я думаю вы легко сможете переносить, копировать, удалять файлы через 7zFM, когда вам проводник Windows ругается на наличие длинных путей.

Обход ограничений длинных путей через 7zFM

Как обойти ограничение длинных путей через символьную ссылку

Такой трюк мы с вами уже проделывали, когда нужно было переносить IMAP профиль у Outlook. Смысл в том, что создается файл в нужном вам месте, и этот файл это просто ярлык ссылающийся на нужный вам файл или папку, после этого путь сокращается и вы можете удалять или создавать все что вам нужно. Откройте командную строку, далее вам нужно иметь два составляющих:

  • Путь где будет лежать файл символической ссылки — в моем примере C:короткий путь
  • Длинный путь — C:ShareWINDOW~1C73D~1C6BF~1 D915~15C04~1B4E5~1260MIC~1

Как обойти ограничение длинных путей через символьную ссылку

Нам поможет команда mklink, где ключ /D создает ссылку на каталог

mklink /D «C:короткий путь» «C:ShareWINDOW~1 C73D~1C6BF~1D915~15C04~1B4E5~1260MIC~1»

Символическая ссылка успешно создана, можно проверять.

Создание символической ссылки для решения проблемы длинных путей

Откройте каталог с укороченным путем и попробуйте создать просто папку, в итоге она будет создана именно по тому длинному пути, как видите легко можно обходить ограничение в 260 символов.

Как в Windows 10 отключить ограничение на длину пути в 260 символов через PowerShell

Как обойти ограничение длинных путей через сопоставление subst

subst — простая команда позволяющая связать нужный путь к каталогу с буквой диска. Так же откройте командную строку в режиме администратора и сопоставьте ваш длинный путь с буквой W.

subst W: «C:ShareWINDOW~1C73D~1C6BF~1 D915~15C04~1B4E5~1260MIC~1»

Как обойти ограничение длинных путей через сопоставление subst

У вас в проводнике Windows должен появиться диск с данной буквой, если его нет, то прочитайте статью «Не появляется диск после команды subst» или просто в проводнике вбейте W: и нажмите Enter.

Как устранить проблему длинных путей Windows

Как обойти ограничение длинных путей через монтирование сетевого диска

В командной строке используйте команду net use, далее буква диска, которую мы присваиваем и в самом конце путь:

net use Z: «\DESKTOP-OJ0SCOEShareWINDOW~1 C73D~1C6BF~1D915~15C04~1B4E5~1260MIC~1» /persistent:yes

Создание сетевого диска ведущего на длинный путь Windows

Как видим все прекрасно отработало и диск появился.

Как обойти ограничение длинных путей через монтирование сетевого диска

Использование утилит Far или Total Commander

После включения параметра «Включить длинные пути Win32» данные утилиты в 100% случаев помог вам произвести любые действия с папками или файлами на любом длинном пути в системе Windows. Откройте Total Commander и создайте для примера папку в каталоге с длинным путем, напоминаю для этого нужно нажать F7.

Использование утилит Far или Total Commander

Как видите все прекрасно создается, удаляется или копируется при желании.

Успешно созданная папка в Total Commander

Как еще обойти проблему с длинными путями Windows

В мир виртуализации и облаков, многие компании переносят свои файловые ресурсы именно туда. Например в моей компании используют для хранения большинства данных это Google Drive, кто-то диски mail.ru или Яндекса, не нужно этого бояться, главное смотрите, чтобы это подходило с юридической точки зрения но и не нужно лукавить это может стоить дополнительных расходов, но зато ни каких длинных путей, вышедших из строя дисков в RAID, место наращивается на лету, короче одни плюсы.

На этом у меня все, мы разобрали как исправляются ошибки «Слишком длинный целевой путь» или «Слишком длинный конечный путь«, с вами был Иван Семин, автор и создатель IT портала Pyatilistnik.org.

If you are facing the error Destination Path Too Long when trying to copy or move a file to a folder in Windows, try the quick trick below. The reason you receive the error is that File Explorer failed to copy/delete/rename any pathname longer than 256 characters.

This is not the limitation of the NTFS file system, but the Win32 API library. In Win32 API the MAX_PATH value is 260. When you try to access file I/O on a specific path, the Windows API always checks if the path is longer than the MAX_PATH limit.

Most standard applications, including Windows Explorer (File Explorer), do not work correctly with long path files exceeding 256 characters. Under the file name, Windows understands the entire path, starting with the root of the drive, ending with the last subfolder, and the file name itself.

When using Unicode API functions, it’s possible to use a path of up to 32767 characters. Thanks to this, many third-party programs (the popular file managers, for example FAR and Total Commander) process files/folders whose path length exceeds 256 characters without any problems.

Note. Some programs use the UNC file path format (prefixed with “?”) to bypass the limitations of the Win32 API. For example, the absolute file path might look like this:

\?C:folder1subfolder1toolongfilename

Due to max path length limitations, the administrator may encounter the following problems:

  • Users can create files and folders in a shared network folder that the administrator (or management scripts) cannot access locally;
  • Errors when synchronizing roaming profiles;
  • Errors in data recovery from shadow copies;
  • Incorrect calculation of the directories size;
  • Loss of files during migration and data transfer between servers, etc.

Full Error:

Destination Path Too Long

The file name(s) would be too long for the destination folder. You can shorten the file name and try again, or try a location that has a shorter path.

destination path too long

Destination Path Too Long error on Windows 10 21H2

Solution 1. Rename Parent Folder to Decrease the Full Path

The simplest way is to shorten the name of the parent folders, by reducing the total path length by simply renaming it. This workaround is not always applicable.

Solution 2. Create a Symbolic Link

Another option is to create a symbolic link to a part of the path, thus shortening the total path length. To create a symbolic link to a folder with a long path, you can use the following command:

mklink /d c:homelink “C:verylongpathhere……”

Now you can perform all file operations (move, rename) with the directory to which the symbolic link is assigned (c:homelink in our case). There will be no path length restrictions when you perform file operations against the symbolic link directory.

Solution 3. Use Subst Utility

Another option is to associate the problem folder to a virtual disk (in our example, Z:), using the built-in utility Subst. Thus, you can also shorten the path length:

Subst Z: “C:verylongpathhere……”

Now you can work with the data on the Z: drive, in which the path to the files won’t exceed the Win32 API path limit. After the job is finished, you can delete the virtual disk using the Subst with the /d option:

Subst Z: /d

Solution 4. Hidden Share Path

Step 1

The quickest fix for this (especially if you need to simply migrate (move) a lot of folders from one place to another) is to map the folder with a long path to a drive letter.

You need to browse the problem folder using the UNC path. This can be either the path to an SMB share, the path to an administrative share available on any Windows computer (for example, \servernamed$usersyour_long_path…), or the NT file naming format (\?d:userslongpath). Copy the folder path to the clipboard.

Note. The “\?” prefix to the path string tells Windows to disable further parsing of the path string and send the path after the prefix directly to the file system driver. In this case, you can bypass the Windows API restrictions and exceed the MAX_PATH limits.

What you should do is browse the hidden share path and copy it to your clipboard.

file path too long

Step 2

Then open File Explorer and select This PC. Click on the Map Network Drive button and select Map network drive. Depending on your OS, it might appear under the tools menu.

the file name would be too long for the destination folder

Step 3

Then simply paste your long folder path, select a drive letter you want to assign, and hit Finish.

destination path too long fix

Step 4

Now you will be able to copy the files/folders into this location without receiving the error.

Solution 5. How to Enable Win32 Long Path in Windows?

In current builds of Windows 10 and 11 (since Windows 10 version 1607) and on Windows Server 2019/2022, it became possible to disable the MAX_PATH limit for manifested win32 and Windows Store apps on the Windows operation system level without using the prefix \?. By default, this feature is disabled.

To enable the built-in support for long paths in Windows 10/Windows Server 2016/2019, use the Regedit.exe editor to set the LongPathsEnabled parameter of REG_DWORD in the registry key HKLMSYSTEMCurrentControlSetControlFileSystem with a value 1.

windows destination path too long

You can change this registry parameter with the following PowerShell command:

Set-ItemProperty -Path HKLM:SYSTEMCurrentControlSetControlFileSystem -Name LongPathsEnabled -Value 1

Or you can enable long path support via the Local Group Policy Editor (Win + R > gpedit.msc > OK). Go to the following GPO section in the Group Policy editor: Computer Configuration > Administrative Templates > System > Filesystem. Open the policy parameter named Enable Win32 long paths and set it to Enabled.

destination path too long windows 10

Enabling Win32 long paths will allow manifested win32 applications and Windows Store applications to access paths beyond the normal 260 character limit per node on file systems that support it. Enabling this setting will cause the long paths to be accessible within the process.

Save the changes and update local group policy settings using gpupdate command.

In both cases, the computer needs to be rebooted to make changes take effect. After a reboot, users and programs will be able to work without restrictions with files, which length of the path exceeds 256 characters. Now the files will only be affected by the NTFS file path limit of 32767 characters.

If you want to check if NTFS long path support is enabled on this computer, you can run the following PowerShell command:

(Get-ItemProperty "HKLM:SystemCurrentControlSetControlFileSystem").LongPathsEnabled

If the command returned a value of 1, then the policy is enabled.

the destination path is too long

Keep in mind, that to use the win32 NTFS long path, the application should be developed with this parameter enabled. As usual, such an option is enabled via the application manifest file.

An application manifest is a small file that contains some information about application compatibility, DPI support, etc. If applications are developed with NTFS long path support, then the longPathAware parameter must be added to the manifest file. For example:

<application xmlns=”urn:schemas-microsoft-com:asm.v3″>

<windowsSettings xmlns:ws2=”http://schemas.microsoft.com/SMI/2016/WindowsSettings”>

<ws2:longPathAware>true</ws2:longPathAware>

</windowsSettings>

</application>

In Visual Studio 2019 and MSBuild 16, this setting is enabled by default.

Once again, we want to draw your attention to the fact that the LongPathsEnabled parameter allows you to bypass the path length restrictions only for Windows applications that do not specify the MAX_PATH variable in the programming codes. This means that Windows Explorer will not work with a long file path even after enabling the “LongPathsEnabled” registry setting or the “Enable Win32 Long Paths” policy setting. To manage files with a long path in File Explorer, you must use one of the tricks described above (symbolic link, substitution, or \?C: path format).

Win32 Long Paths GPO Not Working on Windows 10 File Explorer

There is bad news. File Explorer even in the latest builds of Windows 10 20H2 and Windows Server 2019 still doesn’t support NTFS long paths. This means that when you open such a file/folder, you will still receive the error: “Destination Path Too Long”.

Windows Explorer does not have a declaration in the manifest, and you will have to use one of the tricks described in this article to access long paths in Windows.

We saw the following comment from a Microsoft employee:

This feature is not ready for inclusion in File Explorer. You need to wait until Microsoft turns it on in Explorer, or use a third-party file management tool that is compatible with long paths.

However, in some applications, the MAX_PATH check is embedded in the code. About the max file path restrictions for .Net developers, see Solution 7 below.

Solution 6. Using Robocopy Command Line Tool to Copy and Move Files

You can use the built-in console Windows tool — robocopy to copy or move data. The utility allows you to correctly copy and synchronize files/directories with long paths.

For example, if you cannot delete the directory due to the path length limit, you can first move data from the directory using robocopy:

ROBOCOPY c:folder1folder2folder3longpath c:tmp /MOVE /E

path too long error

After that, you can delete the source directory:

Delete c:folder1folder2folder3longpath /q /f

Solution 7. Long File Path for .Net Developers

The Base Class Library (BCL) of the development environment for the .Net Framework has a built-in preliminary check for the admissibility of long directory and file names. Therefore .Net Framework developers may encounter a System.IO.PathTooLongException error in their programs.

Check for path length removed from BCL code in .Net Framework 4.6.2. Therefore, after updating the version of the .Net Framework, developers can use long paths in the UNC path format (\?C:Very_long_path). When the LongPathsEnabled parameter is enabled in Windows 10/Windows Server 2016, it is possible to work correctly with files that have paths of almost any length.

To do this, use Net Framework 4.6.2 (and newer) when building applications, or use the following application configuration file for older app versions (.Net 4.0):

<?xml version=”1.0″ encoding=”utf-8″?>

<configuration>

<startup>

<supportedRuntime version=”v4.0″ sku=”.NETFramework,Version=v4.0″/>

</startup>

<runtime>

<AppContextSwitchOverrides value=”Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false” />

</runtime>

</configuration>

Solution 8. Long File Path in PowerShell .Net Developers

PowerShell is based on .Net, and in order for the Get-Item, Get-ChildItem, Remove-Item, and other cmdlets to work correctly with long file paths, you need to upgrade the .NET Framework to 4.5 or newer and install Windows Management Framework 5.1.

Tip. The current version of PowerShell can be found in the variable $PSVersionTable.

After that, when using file cmdlets instead of Path, you need to use the LiteralPath parameter. For example:

Get-ChildItem -literalpath \?C:PS

path too long

Solution 9. Use 7-Zip to Perform File Operation with Long File Path

You can use the popular tool for managing 7ZIP to bypass the MAX_PATH restriction in Windows. Install 7-Zip, run the 7zFM.exe app, and paste the path to the problem folder into the address bar.

You can now perform any file operations on files in this directory from the 7-zip GUI. 7-Zip ignores Win32API restrictions on max path lengths.

destination path too long windows 10 fix

Tip #1

There also is a great tool called “Long Path Tool” that works great to fix this. However it isn’t free, the methods above are.

Tip #2

Thank you, Colin Albright, for the comment below. Yes, you can also use 7-zip or any zip utility to fix the Destination Path Too Long problem. Sometimes on single files, this could be a better and faster solution. Just zip the folder up, and you are good to go.

  • About
  • Latest Posts

Brian Jackson started this blog in 2011. Brian has a huge passion for WordPress and technology for over a decade. Brian enjoys blogging, movies, and hiking.


Windows Server 2012 R2 Datacenter Windows Server 2012 R2 Essentials Windows Server 2012 R2 Foundation Windows Server 2012 R2 Standard Windows 8.1 Enterprise Windows 8.1 Pro Windows 8.1 Windows Server 2012 Datacenter Windows Server 2012 Datacenter Windows Server 2012 Standard Windows Server 2012 Standard Windows Server 2012 Essentials Windows Server 2012 Foundation Windows Server 2012 Foundation Windows 8 Enterprise Windows 8 Pro Windows 8 Windows 7 Service Pack 1 Windows Server 2008 R2 Service Pack 1 More…Less

Symptoms

Consider the following scenario:

  • You have a computer that is running Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7 Service Pack 1 (SP1), or Windows Server 2008 R2 Service Pack 1 (SP1).

  • You use Windows Explorer to try to copy files or folders in order to paste them into some other folder.

  • The files or folders that you copy have paths that exceed the maximum allowable path length.


In this scenario, the behavior of the copy operation is unreliable and fails because of the length of the file or folder path. Additionally, you may experience one of the following symptoms:

  • The copy operation fails and generates a message that states that the path (file name) is too long. The message also suggests that you shorten the file name and try to copy again.

  • The copy operation does not start. In this case, no message is generated.

  • The copy operation starts, copies a few files or folders, and then fails without generating a message.

This problem may prevent some files or folders from being copied. You may not realize the the problem occurred if you do not receive an error message. Different symptoms may occur, depending on how the files are selected for copying.

Note This problem can also occur when you try to copy files or folders from Volume Shadow Copy Service snapshots if the file or folder length in the snapshot exceeds the maximum path length.

Cause

This problem occurs because of an issue in how Windows handles the long-path errors.

Resolution

To resolve this issue for Windows 8.1, Windows Server 2012 R2, Windows 8, andWindows Server 2012, install the update rollup.
To resolve this issue for Windows 7 and Windows Server 2008 R2, install the hotfix that is described in this article.

Update information for Windows 8.1, Windows Server 2012 R2, Windows 8, and Windows Server 2012

To resolve this issue, install the update rollup that is dated April 2012 or November 2014.

  • Get the Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 update: April 2014

  • Get the November 2014 update rollup for Windows RT, Windows 8, or Windows Server 2012

Hotfix information for Windows 7 and Windows Server 2008 R2

A supported hotfix is available from Microsoft Support. However, this hotfix is intended to correct only the problem that is described in this article. Apply this hotfix only to systems that are experiencing the problem described in this article. This hotfix might receive additional testing. Therefore, if you are not severely affected by this problem, we recommend that you wait for the next software update that contains this hotfix.

If the hotfix is available for download, there is a «Hotfix download available» section at the top of this Knowledge Base article. If this section does not appear, contact Microsoft Customer Service and Support to obtain the hotfix.

Note If additional issues occur or if any troubleshooting is required, you might have to create a separate service request. The usual support costs will apply to additional support questions and issues that do not qualify for this specific hotfix. For a complete list of Microsoft Customer Service and Support telephone numbers or to create a separate service request, go to the following Microsoft website:

Prerequisites

To apply this hotfix, you must have Service Pack 1 for Windows 7 or Windows Server 2008 R2 installed.

Restart requirement

You must restart the computer after you apply this hotfix.

Hotfix replacement information

This hotfix does not replace any previously released hotfix.

The English (United States) version of this hotfix installs files that have the attributes that are listed in the following tables. The dates and the times for these files are listed in Coordinated Universal Time (UTC). The dates and the times for these files on your local computer are displayed in your local time together with your current daylight saving time (DST) bias. Additionally, the dates and the times may change when you perform certain operations on the files.

Windows 7 and Windows Server 2008 R2 file information and notesImportant Windows 7 hotfixes and Windows Server 2008 R2 hotfixes are included in the same packages. However, hotfixes on the Hotfix Request page are listed under both operating systems. To request the hotfix package that applies to one or both operating systems, select the hotfix that is listed under «Windows 7/Windows Server 2008 R2» on the page. Always refer to the «Applies To» section in articles to determine the actual operating system that each hotfix applies to.

  • The files that apply to a specific product, SR_Level (RTM, SPn), and service branch (LDR, GDR) can be identified by examining the file version numbers as shown in the following table.

    Version

    Product

    SR_Level

    Service branch

    6.1.760
    1.
    22xxx

    Windows 7 and Windows Server 2008 R2

    SP1

    LDR

  • GDR service branches contain only those fixes that are widely released to address widespread, extremely important issues. LDR service branches contain hotfixes in addition to widely released fixes.

  • The MANIFEST files (.manifest) and the MUM files (.mum) that are installed for each environment are listed separately in the «Additional file information for Windows 7 and Windows Server 2008 R2» section. MUM and MANIFEST files, and the associated security catalog (.cat) files, are extremely important to maintain the state of the updated components. The security catalog files, for which the attributes are not listed, are signed with a Microsoft digital signature.

For all supported x86-based versions of Windows 7

File name

File version

File size

Date

Time

Platform

Shell32.dll

6.1.7601.22503

12,875,776

06-Nov-2013

08:00

x86

For all supported x64-based versions of Windows 7 and Windows Server 2008 R2

File name

File version

File size

Date

Time

Platform

Shell32.dll

6.1.7601.22503

14,177,792

06-Nov-2013

08:51

x64

Shell32.dll

6.1.7601.22503

12,875,776

06-Nov-2013

08:00

x86

For all supported IA-64-based versions of Windows Server 2008 R2

File name

File version

File size

Date

Time

Platform

Shell32.dll

6.1.7601.22503

21,196,800

06-Nov-2013

07:58

IA-64

Shell32.dll

6.1.7601.22503

12,875,776

06-Nov-2013

08:00

x86

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the «Applies to» section.

Additional file information for Windows 7 and for Windows Server 2008 R2

Additional files for all supported x86-based versions of Windows 7

File name

X86_5d28b9c19d39486a1a7e115506261602_31bf3856ad364e35_6.1.7601.22503_none_8fa29bae8b68a3a7.manifest

File version

Not Applicable

File size

695

Date (UTC)

06-Nov-2013

Time (UTC)

14:55

Platform

Not Applicable

File name

X86_microsoft-windows-shell32_31bf3856ad364e35_6.1.7601.22503_none_6ec3e88889548dc6.manifest

File version

Not Applicable

File size

1,059,457

Date (UTC)

06-Nov-2013

Time (UTC)

10:12

Platform

Not Applicable

Additional files for all supported x64-based versions of Windows 7 and Windows Server 2008 R2

File name

Amd64_228d6e6efa0f144b0e3153891fddec59_31bf3856ad364e35_6.1.7601.22503_none_3f69116101f5cf33.manifest

File version

Not Applicable

File size

699

Date (UTC)

06-Nov-2013

Time (UTC)

14:56

Platform

Not Applicable

File name

Amd64_ab8a5a310911f0a583d4c1b8a0642dba_31bf3856ad364e35_6.1.7601.22503_none_400593ee3163c592.manifest

File version

Not Applicable

File size

1,040

Date (UTC)

06-Nov-2013

Time (UTC)

14:56

Platform

Not Applicable

File name

Amd64_microsoft-windows-shell32_31bf3856ad364e35_6.1.7601.22503_none_cae2840c41b1fefc.manifest

File version

Not Applicable

File size

1,058,443

Date (UTC)

06-Nov-2013

Time (UTC)

09:16

Platform

Not Applicable

File name

Wow64_microsoft-windows-shell32_31bf3856ad364e35_6.1.7601.22503_none_d5372e5e7612c0f7.manifest

File version

Not Applicable

File size

1,054,916

Date (UTC)

06-Nov-2013

Time (UTC)

08:14

Platform

Not Applicable

Additional files for all supported IA-64-based versions of Windows Server 2008 R2

File name

Ia64_bba4409f672758cfdaf3e6e43606e4d6_31bf3856ad364e35_6.1.7601.22503_none_d273341408e6cde2.manifest

File version

Not Applicable

File size

1,038

Date (UTC)

06-Nov-2013

Time (UTC)

14:55

Platform

Not Applicable

File name

Ia64_microsoft-windows-shell32_31bf3856ad364e35_6.1.7601.22503_none_6ec58c7e895296c2.manifest

File version

Not Applicable

File size

1,058,441

Date (UTC)

06-Nov-2013

Time (UTC)

08:22

Platform

Not Applicable

File name

Wow64_microsoft-windows-shell32_31bf3856ad364e35_6.1.7601.22503_none_d5372e5e7612c0f7.manifest

File version

Not Applicable

File size

1,054,916

Date (UTC)

06-Nov-2013

Time (UTC)

08:14

Platform

Not Applicable

References

Learn about the terminology Microsoft uses to describe software updates.

Need more help?

Практически каждый пользователь Windows рано или поздно сталкивается с ошибкой ″слишком длинный путь″ (path too long). Ошибка эта возникает при работе с файлами или папками, у которых полный путь превышает значение в 260 символов.

Напомню, что полный путь включает в себя букву диска, двоеточие, обратный слэш, имена компонентов (файл, директория) разделенные слешем и завершающий пустой символ (NUL). Выглядит полный путь примерно так:

C:directorysubdirectoryfilename<NUL>

Соответственно, если сумма всех компонентов пути больше 260 символов, то путь считается слишком длинным. Большинство приложений Windows не умеют работать с такими путями и при обращении к файлупапке выдадут примерно такое сообщение:

ошибка "path too long"

Что интересно, значение в 260 символов обусловлено значением MAX_PATH Win32 API. У файловой системы NTFS максимальная длина пути ″немного″ больше и составляет  32767 символов. Для обхода ограничений Win32 API некоторые приложения используют формат UNC, указывая абсолютный путь с префиксом \?, например так:

\?C:directorysubdirectoryfilename

В Windows 10 (начиная с версии 1607) появилась возможность отключить проверку MAX_PATH и использовать длинные пути без префикса \? . Сделать это можно двумя способами — с помощью групповых политик или путем редактирования реестра. Мы рассмотрим оба способа, начнем с политик.

Групповые политики

Первым делом  открываем редактор локальных групповых политик, для чего жмем клавиши Win+R и выполняем команду gpedit.msc.

запуск оснастки локальных групповых политик

Нужная нам политика находится в разделе Конфигурация компьютераАдминистративные шаблоныСистемаФайловая система (Computer configurationAdministrative templatesSystemFilesystem) и называется Включить длинные пути Win32 (Enable Win32 long paths).

выбор политики включения длинных путей

Для активации поддержки длинных путей надо перевести политику в состояние «Включено».

включение политики

Реестр

Для включения поддержки длинных путей через реестр необходимо найти в разделе HKLMSystemCurrentControlSetControlFileSystem параметр с именем LongPathEnabled и задать его значение равным 1.

включение длинных путей через реестр

Эту операцию можно произвести с помощью PowerShell, командой:

Set-ItemProperty -Path HKLM:SYSTEMCurrentControlSetControlFileSystem -Name LongPathsEnabled -Value 1

В обоих случаях потребуется перезагрузить компьютер. После перезагрузки изменения вступят в силу и для путей будет действовать только ограничение файловой системы NTFS (32767 символа), превысить которое вам навряд ли удастся. Однако это вовсе не значит, что можно расслабится. В некоторых приложениях проверка MAX_PATH заложена в коде,  поэтому  по возможности лучше не превышать это ограничение.

Дополнение

Для того, чтобы пользоваться длинными путями, в приложении должна быть включена их поддержка.  Если вы пишите собственное приложение, то для поддержки длинных путей в манифесте приложения надо указать следующие настройки:

<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>

А теперь о грустном. Как внезапно оказалось, в проводнике Windows поддержка длинных путей не реализована!!! Один из разработчиков Microsoft по этому поводу сказал примерно следующее:

″Эта функция не готова для включения в Windows Explorer. Вам нужно подождать, пока Microsoft не включит ее в Explorer, или использовать сторонний инструмент управления файлами, который совместим с длинными путями. ″

Это было сказано еще в 2016 году. Но, судя по всему, разработчики на данную проблему просто забили. На данный момент в версии 1903 проводник все так же не поддерживает длинные пути файлов. Вот так 🙁

Слишком длинное имя файла или слишком длинный целевой путь — как исправить?

Как исправить ошибки слишком длинное имя файла или слишком длинный целевой путьПри копировании, создании, сохранении или перемещении файлов и папок в Windows 11 и Windows 10 на внутреннем HDD или SSD, при копировании данных на внешний диск или флешку, вы можете столкнуться с ошибками вида «Слишком длинный целевой путь. Имена файлов слишком длинны для помещения в эту целевую папку», «Указано неправильное или слишком длинное имя файла» и другие, имеющие отношение к слишком длинным именам или путям к файлам и папкам.

В этой инструкции подробно о том, чем вызваны эти ошибки и как можно их исправить в Windows последних версий, а также дополнительная информация, которая может быть полезной, чтобы решить проблему.

  • Слишком длинное имя файла или слишком длинный целевой путь
    • Причины ошибки и способы её исправить
    • Как включить поддержку длинных путей в Windows
      • В редакторе реестра
      • В редакторе локальной групповой политики
    • Почему ошибка сохраняется при включенной поддержке длинных путей

Причины ошибки «Слишком длинное имя файла» и «Слишком длинный целевой путь» и способы её исправить

Слишком длинный целевой путь при копировании

Несмотря на то, что файловой системой NTFS длина пути ограничена 32760 символов, в Windows существует ограничение на полный путь в 260 символов, включая путь к папке и имя файла с расширением. Ещё одно ограничение — 255 символов на имя файла или отдельной папки. Схожие ограничения есть для файловых систем FAT32 и ExFAT. Когда полный путь к файлу, с которым вы выполняете действия, превышает указанное число символов, вы можете получить сообщение об ошибках о слишком длинном целевом пути или слишком длинном имени файла.

Ошибка Слишком длинное имя файла в Windows

Отсюда основные способы исправить ошибки, связанные с использованием слишком длинного пути:

  1. Использовать более короткие имена файлов и более простое и «компактное» дерево папок.
  2. Включить поддержку длинных путей — такая опция есть в Windows 10 и Windows 11, далее будет рассмотрен порядок действий. Однако, это решит не все проблемы, о чем мы также поговорим.
  3. Использовать файловые менеджеры, которые могут работать с длинными путями по умолчанию: Total Commander, Files (но для него потребуется включить и поддержку длинных путей в системе) или даже 7-Zip File Manager, который прекрасно с этим справляется.

Как включить поддержку длинных путей в Windows 10 и Windows 11

В зависимости от установленной редакции Windows, можно использовать один из следующих способов включения поддержки длинных путей.

В редакторе реестра

Если на вашем компьютере установлена Windows 11 или Windows 10 Домашняя, используйте редактор реестра для включения опции:

  1. Нажмите правой кнопкой мыши по кнопке «Пуск» и выберите пункт «Выполнить» или нажмите клавиши Win+R на клавиатуре, введите regedit и нажмите Enter.
  2. В редакторе реестра перейдите к разделу
    HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlFileSystem
  3. В правой панели редактора реестра дважды нажмите по параметру с именем LongPathsEnabled и присвойте значение 1 вместо 0 для этого параметра. Включить поддержку длинных путей в редакторе реестра Windows
  4. Закройте редактор реестра, перезагрузите компьютер.

В редакторе локальной групповой политики

В Windows Pro и Enterprise можно использовать редактор локальной групповой политики:

  1. Нажмите клавиши Win+R на клавиатуре, введите gpedit.msc в диалоговом окне «Выполнить» и нажмите Enter.
  2. Перейдите к разделу Конфигурация компьютера — Административные шаблоны — Система — Файловая система.
  3. Дважды нажмите по параметру «Включить длинные пути Win32». Политики файловой системы в gpedit
  4. Установите значение «Включено» для этого параметра, примените настройки. Включить поддержку длинных путей в редакторе локальной групповой политики
  5. Закройте редактор локальной групповой политики и перезагрузите компьютер.

Готово, теперь поддержка длинных путей в Windows включена, однако это не означает, что ошибки, с ними связанные, исчезнут.

Почему ошибки длинных путей появляются, несмотря на включенную поддержку длинных путей

Имена файлов слишком длинны для помещения в эту папку

Даже если вы включите поддержку длинных путей к папкам и файлам в Windows 11/10, при действиях с такими файлами в проводнике и некоторых программах вы продолжите получать ошибки вида «Слишком длинный целевой путь. Имена файлов слишком длинны для помещения в эту целевую папку» или «Указано неправильное или слишком длинное имя файла», также будут недоступны некоторые действия в папках, имеющих длинный путь.

Причина этого — поддержка длинных путей требуется не только на уровне системы, но и в самой программе, которая работает с этими путями, в качестве примера:

  • Проводник не сможет полноценно работать с длинными путями даже при включенной поддержке.
  • Файловый менеджер Files из магазина приложений будет исправно работать, если включить поддержку длинных путей, и будет сообщать об ошибках при отключенной поддержке. Работа с длинными путями в файловом менеджере Files
  • Total Commander или встроенный файловый менеджер 7-Zip работают с длинными путями независимо от того, включена ли их поддержка в Windows.

То же самое касается не только файловых менеджеров, но и прикладных программ: текстовых, графических и видео редакторов и другого ПО.

Надеюсь, инструкция прояснила причины ошибки и возможные способы решения проблемы. Если же вопросы остаются — жду их в комментариях.


Table of Contents

  • .NET Error: Path too Long
  • NET 4.6.2 and long paths on Windows 10
  • Other .NET libraries which support long path
    • QuickIO.NET
    • AlphaFS
  • Use Robocopy as a workaround
  • Use a Share or a substitution as a workaround
  • PowerShell Path too Long and .NET
  • PowerShell Robocopy Clone .NET
  • See Also

.NET Error: Path too Long

Since .NET 4.6.2 on Windows 10 there is a solution (see below)

Some of you may know the famous error “System.IO.PathTooLongException“.

The path is too long after being fully qualified. Make sure path is less than 260 characters.

This is by design from the Windows API and the .NET Framework.

Naming Files, Paths, and Namespaces:
http://msdn.microsoft.com/en-us/library/aa365247.aspx

The Windows API Function CreateFileEx from the Kernel32.dll utilizes Unicode.  By appending the string «\?» in front of the path, this API Function can handle up to 32,000 characters.

See: http://blogs.msdn.com/b/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx

You can list long paths using the \?c: syntax in cmd.exe!

dir \?c: /s

PowerShell and cmd.exe:

$foldernames=cmd /c ‘dir \?c: /s /ad |findstr «\\?\»‘

The prefix of \? is not supported within .Net at the time of writing (as of version 4.0).

So you can not simply append the string «\?» to your normal Path! This will only work with the mentioned Windows API Function!

Otherwise, you will get the error «Illegal characters in path.» !

You can try to use the .NET Classes System.IO.Directory.GetFiles() and System.IO.Directory.GetDirectories()

They both return back string arrays of the full path of the files and directories respectively.

As long as you don’t need the additional properties, as in this case, this is the easiest solution to the problem.

See:
http://aspadvice.com/blogs/davidwalker/archive/2007/01/22/PathTooLongException-work-around.aspx

If you can’t live with that, there is a Project on Codeplex from the .NET Base Class Library (BCL) Team.

The work there is in the conceptual state and there is no further development, but you can use it if you are a .NET Developer:

See: http://bcl.codeplex.com/releases/view/42783?ProjectName=bcl

Read the Blog Post of the BCL Team:

  • Long Paths in .NET, Part 1 of 3
  • Long
    Paths in .NET, Part 2 of 3: Long Path Workarounds

  • Long
    Paths in .NET, Part 3 of 3 Redux

There is also a library that encapsulates all this work over at google code called zeta long paths

See: http://code.google.com/p/zetalongpaths/

NET 4.6.2 and long paths on Windows 10

Long paths aren’t enabled by default yet. You need to set a policy to enable support.

To do this you want to «Edit group policy» in the Start search bar or run «gpedit.msc» from the Run command (Windows-R).

In the Local Group Policy Editor navigate to «Local Computer Policy: Computer Configuration: Administrative Templates: All Settings».

In this location, you can find «Enable Win32 long paths».

After you’ve turned this on you can fire up a new instance of PowerShell and free yourself from the constraints of MAX_PATH!

The key File and Directory Management APIs respect this and now allow you to skip the check for MAX_PATH without having to resort to using «\?»

This is also possible as PowerShell has opted into the new .NET path support (being that it is a .NET application).

In .NET 4.6.2 there will no longer throw PathTooLongException if a path is >= MAX_PATH.

If the OS doesn’t like it we’ll surface whatever the OS returns as an error (which may be PathTooLong)..

In many cases, the OS will return DirectoryNotFound for paths that are too long. The primary case is with creating files.

In .NET 4.6.2 there is no way to programmatically check whether paths are actually too long so there is no Translation between DirectoryNotFound into PathTooLong.

JeremyKuhne wrote Articles about this Topic:

  • More on new .NET path handling
  • .NET 4.6.2 and long paths on Windows 10

Other .NET libraries which support long path

Extra Tip:

The original .NET classes for the file system are working very slow.

If you need more speed you have to use the following .NET libraries or use the Microsoft Robocopy.exe

QuickIO.NET

QuickIO.NET is a library to replace the file system classes of the .NET Framework, with nearly identical signatures of the native .NET methods.

QuickIO.NET focuses on performance and comfortable dealing with the file system.

In addition to the fast communication with the Win32 API and browsing the file system quickly and efficiently,

QuickIO.NET provides methods to read, write, edit, move, compress, split files and directories — and many many more.

Why QuickIO.NET is useful for you and your application much faster browsing of folder structures (up to 30x faster)

  • Lightning-fast retrieve of metadata of folders, files, and directory structures
  • File chunk support for reading, comparisons, and hashing.
  • Data transfer services monitored file and directory copy/move with progress events
  • Custom service and job support (via extensions and own implementation)
  • Long path support (UNC paths) up to 32767 characters
  • Calculate checksums of files and file chunks
  • Fully tested source code using UnitTests
  • Nearly identical signature of methods to native .NET
  • Async Operations (requires .NET 4.0 or above)
  • Multiple releases from .NET 2.0 to .NET 4.5
  • Well documented
  • Open Source License (MSPL)

More info

  • https://quickio.codeplex.com, or
  • http://quickio.azurewebsites.net/

AlphaFS

AlphaFS is a .NET library providing more complete Win32 file system functionality to the .NET platform than the standard System.IO classes.

The file system support in .NET is pretty good for most uses. However, there are a few shortcomings, which this library tries to alleviate. The most notable deficiency of the standard .NET System.IO is the lack of support of advanced NTFS features, most
notably extended-length path support (eg. file/directory paths longer than 260 characters).

Feature Highlights

  • Support for extended length paths (longer than 260 characters)
  • Creating Hardlinks
  • Accessing hidden volumes
  • Enumeration of volumes
  • Transactional file operations
  • Support for NTFS Alternate Data Streams
  • Accessing network resources (SMB/DFS)
  • …and much more!

See: https://github.com/alphaleonis/AlphaFS

Use Robocopy as a workaround

There is an Article at the PowerShell Magazine that shows how to use Robocopy as a workaround

Parse Robocopy output in PowerShell to find long path names – Workaround for 260 character limit in Windows

http://www.powershellmagazine.com/2012/07/24/jaap-brassers-favorite-powershell-tips-and-tricks/

In the following example, we use Robocopy in the virtual mode with the option /l ($env:Temp is never used) .

The Option /l Specifies that files are to be listed only (and not copied, deleted, or time-stamped).

So all work is done only in Computer memory and not in the File system. This is really fast!

This example is to calculate the size of a folder incl. all subfolders. This works even with long pathes!

The Text output of Robocopy is examined and splited so that PowerShell gets only the amount of bytes.

Text processing is error-prone! You can even use the Robocopy Clone mentioned below!

1.$Ordner =
'c:program files'

2.(robocopy.exe $Ordner $env:Temp /zb /e
/l /r:
1 /w:1
/nfl /ndl /nc /fp /bytes /np /njh) | Where-Object {$_ -like
"*Bytes*"} | ForEach-Object { (-split $_)[1] }

See:
http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/30efc904-0aea-454e-a8d0-60408258126e/

Use a Share or a substitution as a workaround

You can access a Long Path even if you create a Share on a deep point of the Path.

Then you can use the Share to access files which are deeper than that point.

For example, if you create a Share or a drive substitution with «Subst» on a Folder, with the depth of 250 characters than you can access the rest of the Path by use of the Share. (But even that may fail)

PowerShell Path too Long and .NET

The MVP Joel ‘Jaykul’ Bennett picked up the work of the BCL Team and developed a PowerShell Module with a minimalistic set of PowerShell Cmdlets to deal with Long Paths.

See: http://huddledmasses.org/long-path-module-experimental-io/

PowerShell Robocopy Clone .NET

The MCT Ingo Karstein even picked up the work of the BCL Team and developed a full-blown Open source .NET PowerShell Robocopy Clone:

And here on Codeplex

  • See: http://robopowercopy.codeplex.com/

This .NET Robocopy Clone supports even Path length up to 32,000 characters, but it is not very fast.

  • See further:
    http://stackoverflow.com/questions/8755920/alternative-to-directory-createdirectorypath-supporting-long-paths

See Also

  • PowerShell Portal
  • Wiki: Portal of TechNet Wiki Portals

При попытке скопировать, переместить и удалить файлы или папки система может заблокировать это действие ошибкой «слишком длинный целевой путь». Она возникает по причине того, что Windows имеет ограничение на длину пути, число символов в котором не должно превышать 260 символов.

Проблема возникает на уровне вложенности приложений и не связана с ограничением NTFS. В этом случае количество символом ограничивается библиотекой Win32 API. Поэтому большинство стандартных приложений, включая проводник Windows, не будут обрабатывать объекты, длина пути к которым превышает 260 символов.

Содержание

  • 1 Переименование расширений
  • 2 Удаление с помощью утилиты DeleteLongPath
  • 3 Включение поддержки для работы с глубоко вложенными объектами
  • 4 Использование команды xcopy

Переименование расширений

Если ошибка возникает при перемещении архивных файлов Zip или Rar, попробуйте временно переименовать их в формат «txt» и после переноса вернуть обратно.

Для этого щелкните правой кнопкой мыши на архив и выберите «Переименовать». Затем измените расширение на «txt».

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

После перемещения файла, верните ему первоначальное расширение (zip или rar).

Если этим способом не удалось переместить архивы по причине слишком длинного целевого пути, перейдите к следующему решению.

Удаление с помощью утилиты DeleteLongPath

Если нужно удалить папку, которая вложена по слишком длинному пути, попробуйте сделать это с помощью бесплатной утилиты DeleteLongPath. Она предназначена для удаления структуры папок и всех содержащихся в ней вложенных объектов.

Сделайте запрос в интернете «DeleteLongPath» и перейдите на указанный сайт.

После загрузки извлеките файл из zip-архива и откройте.

Кликните на кнопку «Обзор», чтобы указать расположение папки, и нажмите на «Удалить». В следующем окне подтвердите действие, и дождитесь завершения удаления.

Включение поддержки для работы с глубоко вложенными объектами

В Windows 10 (сборка 1607 и выше) есть возможность отключить ограничение MAX_PATH на системном уровне. Выполните следующие шаги.

Откройте Редактор реестра командой regedit из окна «Выполнить» (Win + R).

Раскрывая вложенную структуру на левой панели, перейдите в следующий раздел:

HKEY_LOCAL_MACHINE – SYSTEM – CurrentControlSet – Control – FileSystem

В разделе FileSystem дважды кликните на параметре LongPathsEnabled, чтобы перейти в его установки.

В поле «Значение» установите «1» и примените изменения на «ОК».

Закройте Редактор реестра и попробуйте выполнить действия с папками, которые не удавались из-за ошибки слишком длинного целевого пути.

Использование команды xcopy

Если по-прежнему не удается скопировать папку, целевой путь к которой слишком длинный, попробуйте это сделать с помощью команды xcopy, запущенной из командной строки с правами администратора.

Запустите командную строку от имени администратора с помощью системного поиска.

В консоли запустите следующую команду:

xcopy *путь к источнику* *папка назначения* /O /X /E /H /K

Копирование должно произойти без ошибки.

Понравилась статья? Поделить с друзьями:
  • Error unable to write to destination
  • Error unable to write ibec 3utools
  • Error unable to validate saml message
  • Error unable to unlink old git
  • Error unable to switch dfu mode to recovery mode