Disable windows path length limit

Время на прочтение
4 мин

Количество просмотров 69K

Многим пользователям ПК под управлением ОС Windows, не говоря о разработчиках, знакомы проблемы при работе с длинными (более 260 символов, MAX_PATH) путями файлов или каталогов.

В данной статье рассматриваются способы избавления от этого пережитка при разработке приложений на различных платформах (WinApi, .Net Framework, .Net Core) и активации нативной поддержки длинных путей в Windows 10 (Anniversary Update).

Приложения Win API

В приложениях, которые используют Win API для работы с файлами, рецепт избавления от ограничения MAX_PATH был известен с незапамятных времён – необходимо было использовать Unicode версию функции с окончанием «W» для работы с директорией или файлом и начинать путь с префикса \\?\. Это давало возможность использовать пути длинной до 32767 символов.

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

Это коснулось следующих функций:

Для работы с каталогами: CreateDirectoryW, CreateDirectoryExW, GetCurrentDirectoryW, RemoveDirectoryW, SetCurrentDirectoryW. И для работы с файлами: CopyFileW, CopyFile2, CopyFileExW, CreateFileW, CreateFile2, CreateHardLinkW, CreateSymbolicLinkW, DeleteFileW, FindFirstFileW, FindFirstFileExW, FindNextFileW, GetFileAttributesW, GetFileAttributesExW, SetFileAttributesW, GetFullPathNameW, GetLongPathNameW, MoveFileW, MoveFileExW, MoveFileWithProgressW, ReplaceFileW, SearchPathW, FindFirstFileNameW, FindNextFileNameW, FindFirstStreamW, FindNextStreamW, GetCompressedFileSizeW, GetFinalPathNameByHandleW.

Это избавляет от необходимости использовать префикса \\?\ и потенциально даёт шанс приложениям, работающим напрямую или косвенно через Win API, получить поддержку длинных путей без необходимости их пересборки. Как активировать эту возможность описано в конце статьи.

.Net Framework

Хотя .Net Framework и использует Win API для работы с файлами — предыдущее изменение не принесло бы результата, т.к. в код BCL встроены предварительные проверки на допустимость длинны имён каталогов и файлов, и до вызова функций Win API дело даже не доходило, выдавая известное исключение. По многочисленным просьбам сообщества (более 4500 на UserVoice) в версии 4.6.2 из кода BCL вырезали проверки ограничения длинны пути, отдав это на откуп операционной и файловой системам!

Вот что это даёт:

  • При использовании префикса “\\?\” мы можем работать с длинными путями как в Win API,
    Directory.CreateDirectory("\\\\?\\" + long_dir_name);
  • Если активировать нативную поддержку длинных имен файлов Windows 10 (1607), то даже не потребуется использовать префикс!

Как включить:

  • Использовать .Net Framework 4.6.2 как цель при сборке приложения.
  • Использовать конфигурационный файл, например, если приложение уже было собрано под .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>

.Net Core

Тут поддержку длинных путей анонсировали ещё в ноябре 2015 года. Видимо сказалось Open Source природа проекта и отсутствие строгой необходимости обеспечения обратной совместимости.

Как включить:
Всё работает из коробки. В отличие от реализации в .Net Framework – тут нет необходимости в добавлении префикса “\\?\” – он добавляется автоматически при необходимости.

Вот тут можно посмотреть пример.

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

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

Включить встроенную поддержку длинных путей можно создав или изменив следующий параметр системного реестра: HKLM\SYSTEM\CurrentControlSet\Control\FileSystem Параметр LongPathsEnabled (Тип: REG_DWORD) 1 – соответствует значению включено.

Или через групповые политики (Win+R\gpedit.msc) Computer Configuration > Administrative Templates > System > Filesystem > Enable NTFS long paths.Оно же в локализованном варианте: Конфигурация компьютера > Административные шаблоны > Система > Файловая система > Включить длинные пути Win32.

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

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

С CMD, к сожалению, это не сработает, на данный момент, из-за особенностей работы с путями, а в PowerShell должно всё заработать.

P.S.

На этом мой небольшой пятничный пост заканчивается, оставив за рамками вопросы полноты реализации поддержки длинных путей в Windows 10 (1607), или работоспособность при использовании различных комбинаций редакций Windows, файловых систем и API. По мере поступления новых фактов и результатов экспериментов пост будет обновляться.

Спасибо за внимание!

Большинство администраторов и пользователей Windows при работе с файлами, так или иначе сталкивались с ошибкой “path too long”. Эта ошибка возникает при превышении полного пути к файлу (вместе с его именем) значения 260 символов. Многие приложения, в том числе проводник Windows, неправильно работают с такими длинными именами файлов, оказываясь их открывать, перемещать и удалять. Это ограничение не файловой системы NTFS, а библиотеки Win32 API (подробнее о проблеме и обходных способах ее решения рассказано здесь).

В новой сборке Windows 10 Insider Preview Build 14352 доступной участникам программы Windows Insider, появилась новая возможность отключить ограничение на максимальную длину пути.

Отключить ограничение MAX_PATH можно двумя способами: с помощью редактора групповых политик или через реестр. Рассмотрим оба:

  1. Запустите консоль редактора локальной групповой политики, нажав Win+R и выполнив команду gpedit.msc
  2. Перейдите в раздел редактора Local Computer Policy -> Computer Configuration -> Administrative Templates -> System -> Filesystem -> NTFS (Конфигурация компьютера -> Административные шаблоны -> Система -> Файловая система -> NTFS)Групповые политики NTFS
  3. Откройте политику Enable NTFS long pathsEnable NTFS long paths включить поддержку путей более 260 символов
  4. Включите политику, переведя ее в состояние Enabled
  5. Сохраните изменения

При использовании домашней версии Windows 10, в которой отсутствует редактор GPO, это же изменение можно внедрить с помощью редактора реестра.

  1. Запустите редактор реестра regedit.exe
  2. Перейдите в ветку HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects\{48981759-12F2-42A6-A048-028B3973495F}Machine\System\CurrentControlSet\Policies
  3. Создайте в данной ветке новый параметр типа Dword (32-bit) Value с именем LongPathsEnabledLongPathsEnabled - параметр реестра
  4. Чтобы отключить ограничение MAX_PATH, измените значение ключа на 1
  5. Также вы можете включить эту функцию одной командой PowerShell:
    Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem -Name LongPathsEnabled -Value 1

Для вступления изменений в силу в обоих случаях требуется перезагрузка компьютера. После перезагрузки пользователи и программы смогут без ограничений работать с файлами, длина пути к которым превышает 260 символов. Теперь на файлы будет действовать только ограничение файловой системы NTFS – 32767 символов .

Этот функционал доступен всем пользователям Windows 10, начиная с Anniversary Update (1607), и в Windows Server 2016.

Download Windows Speedup Tool to fix errors and make PC run faster

Do you know that you can only have 260 characters in a path on Windows 11/10? If you are having issues with this limitation and searching for a way to enable Win32 Long Paths, this is the guide for you.

It is by default in Windows that you cannot access a path that is longer than 260 characters. That includes path and file name. You may see The file name(s) would be too long for the destination folder type of error messages. Now for a normal user, it is not a problem. But for some people who name their files with longer names, it will be a problem. The only solution for them is to enable NTFS or Win32 Long Paths in Windows 11/10.

There are two ways we can use to enable or disable Win32 long paths in Windows 11/10.

    1. Through Regedit
    2. Through Local Group Policy Editor

Let’s see how we can enable or disable through them.

Make Windows accept File Paths over 260 characters

Enable Win32 Long Paths through Regedit

To enable Win32 long paths through Regedit-

  1. Open Regedit
  2. Paste the path for the file system folder
  3. Find the LongPathsEnabled DWORD file and double click on it
  4. Change to value from 0 to 1 and click OK

Let’s get into the details of the process.

Click on the Start Menu and type RegEdit. You will see Registry Editor in the results. Open it.

In the Registry Editor windows paste the following path to the FileSystem folder in the address bar and press Enter.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem

Path for file system regedit

In the FileSystem folder, find the LongPathsEnabled and double-click on it.

How to Enable Win32 Long Paths in Windows 11/10

You will see a small DWORD window. Change the value from 0 to 1 and click on OK to save the changes.

change values in DWORD

It will enable long paths on your PC. If you want to disable it, you can change the value from 0 to 1 anytime.

Read: Source Path Too Long? Use SuperDelete to delete files with such errors.

Fix: Path too long Error 0x80010135

Enable Win32 Long Paths through Local Group Policy Editor

To enable Win32 Long Paths through gpedit or Local Group Policy Editor,

  1. Search for gpedit and open it from the Start Menu or Run box
  2. Click on the Filesystem folder on the sidebar
  3. In the files of Filesystem, double-click on Enable Win32 long paths
  4. Check the radio button beside Enabled
  5. Click on OK to save the changes

Let’s get into the process of details.

Click on the Start Menu and search for gpedit.msc and open it from the search results.

In the Local Group Policy Editor window, go to:

Computer Configuration > Administrative Templates > System > Filesystem.

In the components of the Filesystem folder, double click on Enable Win32 long paths to open it.

Enable Win32 Long paths gpedit

Then, in the Enable Win32 long paths window, check the radio button beside Enabled to enable long paths and click on OK at the bottom of the window to save the changes.

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.

Enable long paths through gpedit

It will enable long paths on your PC. You can disable the long paths anytime by checking the radio button beside Disabled.

Do note that Windows Home editions do not have Group Policy Editor. You need to add it.

TIP: Long Path Fixer tool will fix Path Too Long errors.

Anand Khanse is the Admin of TheWindowsClub.com, a 10-year Microsoft MVP (2006-16) & a Windows Insider MVP (2016-2022). Please read the entire post & the comments first, create a System Restore Point before making any changes to your system & be careful about any 3rd-party offers while installing freeware.

Table of Contents

  • Option #1: Make your base path shorter
  • Option #2: Enable the NTFS/Win32 long paths policy
    • Before Anniversary Update
    • After Anniversary Update
  • Option #3: Modify your Windows Registry File
  • Conclusion

If you’re a Windows developer, system administrator or seasoned user, there’s  good chance you’re fully aware of the 255-260 character limit of filesystem paths. However, in case you never heard about it, here’s a small recap of the issue:

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is «D:\some 256-character path string<NUL>» where «<NUL>» represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.) [extract from this MSDN official guide].

If you’re a standard user, chances are you won’t get bothered by this limitation: who needs these long paths anyway? However, if you happen to be a developer working with linux-native package managers such as NPM, you will be struck by that issue sooner or later. That’s because there are many popular script-based libraries which make an intensive use of folder-nesting: AngularJS, Angular2, React and SystemJS, just to throw out some good examples. If you use them with Visual Studio 2015, which will adds their solution/project folder structure to the loop, the chance of hitting that limit will be even higher.

As soon as this happens your system will be unable to properly access these files and you’ll face a number of frustrating issues: Visual Studio crashes, build errrors, IIS errors and more. The scenario will be even worse if you’re using task runners or other tools to automate IO tasks for debug and/or release purposes, because they will also be unable to read, move, copy, delete or do any kind of work within these path, throwing a number of exceptions that will most certainly give you more than an headache.

This is a common example of an error related to the 255-260 characters limit being hit (from the Visual Studio crash log):

-> (Inner Exception #1) System.InvalidOperationException: The item metadata «%(FullPath)» cannot be applied to the path «<very long path here>». <very long path here>

at Microsoft.Build.Shared.ErrorUtilities.ThrowInvalidOperation(String resourceName, Object[] args)

at Microsoft.Build.Shared.ErrorUtilities.VerifyThrowInvalidOperation(Boolean condition, String resourceName, Object arg0, Object arg1, Object arg2)

at Microsoft.Build.Shared.FileUtilities.ItemSpecModifiers.GetItemSpecModifier(String currentDirectory, String itemSpec, String definingProjectEscaped, String modifier, String& fullPath)

at Microsoft.Build.Evaluation.BuiltInMetadata.GetMetadataValueEscaped(String currentDirectory, String evaluatedIncludeBeforeWildcardExpansionEscaped, String evaluatedIncludeEscaped, String definingProjectEscaped, String name, String& fullPath)

And this is a standard  «Visual Studio has crashed» popup warning that you might get for the same reason:

Enable NTFS or Win32 long paths policy to remove the 255-260 characters limit in Windows 10

Now that we successfully identified the issue, let’s see what workarounds we can use to overcome this.

Option #1: Make your base path shorter

It might sound obvious, but it’s entirely possible that you can fix your issue by shorten your base path. You cannot easily change the NPM packages folder structure (you should never do that), yet you can always move your project to a different location on your hard drive.

For example, if you keep your solution in


C:\Users\<Your Username>\Documents\Visual Studio 2015\Solutions\

, you can easily move everything to

C:\Solutions\

and shorten all your project paths by a good amount of characters.

If you don’t want to mess up your working paths you can also use a good alternative, assuming you’re using Windows 10: enable the NTFS long paths policy (or Win32 long paths policy, depending on the Windows 10 build) and get rid of these limits for good.

According to Microsoft, «enabling NTFS/Win32 long paths allows manifested win32 applications and Windows Store applications to access paths beyond the normal 260 char limit per node.»

This is precisely what we need, isn’t it? Enable this feature isn’t hard, but it will require us to make some edits to the Windows Group Policies using the Group Policy editor. These are the required steps:

Before Anniversary Update

If you’re running a Windows 10 build between 14352 and RTM 1607, aka «Anniversary Update», you need to do the following:

  • Launch the Group Policy Editor by pressing Windows Key and manually typing gpedit.msc, then hit the Enter key.
  • Navigate to Local Computer Policy > Computer Configuration > Administrative Templates > System > Filesystem > NTFS.
  • Locate the Enable NTFS long paths option and enable it with a click.

As an alternative, you can also achieve the same results by executing the following registry commands:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\FileSystem]

«LongPathsEnabled»=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem]

«LongPathsEnabled»=dword:00000001

After Anniversary Update

If you’re running a post-Anniversary Update Windows 10 build (RTM 1067 or newer), you need to use the following:

  • Launch the Group Policy Editor by pressing Windows Key and manually typing gpedit.msc, then hit the Enter key.
  • Navigate to Local Computer Policy > Computer Configuration > Administrative Templates > System > Filesystem.
  • Locate the Enable Win32 long paths option and enable it with a click.

Enable NTFS or Win32 long paths policy to remove the 255-260 characters limit in Windows 10

This should fix your issue for good.

Option #3: Modify your Windows Registry File

If you don’t want to mess with the Group Policy editor, you can use this alternative method and apply the relevant changes directly on your Windows registry file.

  • Launch regedit.exe from a command-prompt or using the Run app.
  • Navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem
  • Add a new DWORD key and call it LongPathsEnabled — if such key already exists, skip this step.
  • Give the LongPathsEnabled DWORD key a value of 1 to Enable the long file names support.
  • Reboot your system.

A great advantage of this method is the fact that it works even with non-pro editions of Windows 10, such as Windows 10 Home — where the Local Group Policy Editor is not available.

It goes without saying that, in order to have such feature disabled, you’ll just have to open your Windows registry file again and delete that key.

Conclusion

That’s it for now: we hope that this small guide will help those who are struggling to enable the support for long file pathnames on their Windows 10 system.

  1. Should I disable the path length limit?
  2. What is disable Windows path length limit?
  3. How do I turn off path limit in Windows 10?
  4. How do I fix Windows path too long and file name is too long?
  5. What is Max path limitation?
  6. What is the maximum file path length in Windows 10?
  7. What is the maximum length of a filename in Windows?
  8. How do I increase the maximum path in Windows?
  9. How do you get past the destination path too long?
  10. How do I get Windows 10 to accept file paths over 260 characters?
  11. How long can a Windows file path be?

Should I disable the path length limit?

Essentially what it does is it lets Python ignore the ancient 260 character filepath length limit. If Python is installed somewhere that requires more than that amount of characters, it won’t work from PATH unless the limit is disabled. In other words, I recommend disabling the limit. It very likely can’t hurt.

What is disable Windows path length limit?

I am here to help you today. Disable the path limit length is recommended after Python setup is successful, because if python was installed in a directory with a path length greater than 260 characters, adding it to the path could fail. So don’t worry about that action and proceed to it.

How do I turn off path limit in Windows 10?

With the Anniversary Update of Windows 10, you can finally abandon the 260 character maximum path limit in Windows. You just need to make a minor edit to the Windows Registry or Group Policy.

How do I fix Windows path too long and file name is too long?

How To Fix: «The File Name Is Too Long» (In Windows Explorer)

  1. STEP 1 — Locate The File That Is Giving You That Error.
  2. STEP 2 — Now That You Know The Location Of The File, Go To A Parent or Top Level Folder. …
  3. STEP 3 — Rename Parent Folder To Something Short Enough To Reduce The Character Count Below 260 characters.

What is Max path limitation?

In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character.

What is the maximum file path length in Windows 10?

Maximum Path Length Limitation

In editions of Windows before Windows 10 version 1607, the maximum length for a path is MAX_PATH, which is defined as 260 characters. In later versions of Windows, changing a registry key or using the Group Policy tool is required to remove the limit.

What is the maximum length of a filename in Windows?

The Windows API imposes a maximum filename length such that a filename, including the file path to get to the file, can’t exceed 255-260 characters.

How do I increase the maximum path in Windows?

Go to Windows Start and type REGEDIT. Choose the Registry Editor. In the Registry Editor, navigate to the following location: at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem.

Choose the DWORD (32-bit) Value.

  1. Right-click the newly added key and choose Rename.
  2. Name the key LongPathsEnabled.
  3. Press Enter.

How do you get past the destination path too long?

Fix: Destination path too long error

  1. Method 1: Shorten the name of the parent folder.
  2. Method 2: Temporarily rename the file extension to text.
  3. Method 3: Delete folder with DeleteLongPath.
  4. Method 4: Enable Long Path Support (Windows 10 built 1607 or higher)
  5. Method 5: Using the xcopy command in an elevated Command Prompt.

How do I get Windows 10 to accept file paths over 260 characters?

How to enable paths longer than 260 characters in Windows 10

  1. Hit the Windows key, type gpedit. msc and press Enter.
  2. Navigate to Local Computer Policy > Computer Configuration > Administrative Templates > System > Filesystem > NTFS.
  3. Double click the Enable NTFS long paths option and enable it.

How long can a Windows file path be?

The maximum length for a path (file name and its directory route) — also known as MAX_PATH — has been defined by 260 characters. But with the latest Windows 10 Insider preview, Microsoft is giving users the ability to increase the limit.

  • Disk error press any key to restart при установке windows с флешки
  • Disable windows firewall in windows 10
  • Disk drill для windows торрент
  • Discord запускается вместе с windows как отключить
  • Disable windows fast startup windows 10