Максимальное количество символов в названии файла windows

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

Категория ~
Фундаментальные статьи – Автор:

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

Ограничение длины файлов в Windows особенности и тонкости

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

Примечание: Если вы не знали, то в большинстве файловых систем каталог — это разновидность файла, но с нулевым размером данных.

Существует множество различных файловых систем, каждая из который по-своему определяет структуру имени файла, включая способ построения пути к файлу. К примеру, на небольших usb устройствах хранения данных, обычно, используется система FAT32. А на оптических дисках (CD/DVD) обычно используется UDF или ISO 9660. На системных дисках последних ОС Windows используется файловая система NTFS, которая и станет предметом данной статьи (как наиболее распространенная для Windows).

Примечание: К примеру, на системных дисках с Windows XP, часто, использовалась файловая система FAT32. Однако, у нее был существенный (для сегодняшнего времени) недостаток — это ограничение на максимальный размер файла в 4 Гб. NTFS же не имеет такого ограничения.

Существует некоторая путаница в цифрах максимальной длины имени файла в файловой системе NTFS, которую вы можете обнаружить в различных источниках. Для начала, есть абсолютный предел, введенный Windows API, и он составляет 260 символов. Тем не менее, практический пределе меньше, чем 260 символов. Например, все имена должны иметь нулевой терминатор в конце. Обычно, этот маркер видит только Windows, но он все равно воспринимается, как один символ. Таким образом ,у вас есть только 259 доступных символов. Еще три символа используются для указания диска (например, C:). Таким образом, реальный предел для имени, содержащего все каталоги, включая вложенные, и название самого файла вместе с расширением, уменьшается до 256 символов.

Примечание: Windows API — ядровой интерфейс, на котором строится вся операционная система и который используют программы.

Тем не менее, есть еще одна тонкость, связанная с тем, как Windows кодирует символы. Ни один индивидуальный объект (файл или каталог) не может иметь имя длиннее 255 символов. При этом, имя включает в себя пробелы и обратную косую черту, которая используется в качестве разделителей. Этот предел в 255 символов часто цитируется, как предел для названия отдельного файла, но, на практике, это относится только к именам файлов в корневом каталоге без каких-либо каталогов.

Существует и еще одно ограничение на длину имени файла, которое часто упускается из виду. Обычно, по умолчанию Windows поддерживает альтернативное имя файла, используя старую систему именования 8.3. Когда вы создаете папку, Windows будет резервировать 12 символов для альтернативного имени файла, оставляя 244 символов для всех содержащихся внутри объектов. Использование системы именования 8.3 можно отключить, но это может вызвать проблемы, при использовании старых 16-битных программ.

Примечание: Система именования 8.3 довольно проста. 8 — это количество символов наименования. «.» — это разделитель между названием и расширением. 3 — это количество символов для расширения. 12 — это 8 + 1 + 3.

Примечание: Подробнее о том, как отключить поддержку 8.3, смотрите информацию по адресу https://technet.microsoft.com/ru-ru/library/cc778996.aspx. Учтите, что вам потребуется редактировать реестр.

Существует так же механизм, который позволяет использовать более длинные имена файлов. Например, сетевым системам, порой, требуется больше гибкости в именах файлах. Поэтому, Windows API включает в себя специальную систему обращения для поддержки очень длинных Unicode имен в блоках по 255 символов. Эти длинные имена начинаются с префикса «\?» (без кавычек). Так что, если вы столкнулись с проблемой в имени файла, у которого длина слишком большая, то попробуйте использовать этот префикс в имени пути, например, «\?c:file.txt» (без кавычек).

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

☕ Понравился обзор? Поделитесь с друзьями!

  • Типы программ резервирования: какая разница между образом диска, файловым бэкапом и синхронизацией, и какой тип стоит использовать?Типы программ резервирования: какая разница между образом диска, файловым бэкапом и синхронизацией, и какой тип стоит использовать?
    Фундаментальные статьи
  • Что такое RSS и как его использовать?Что такое RSS и как его использовать?
    Фундаментальные статьи
  • Что означает портативное приложение (portable)?Что означает портативное приложение (portable)?
    Фундаментальные статьи
  • IP-адрес и его особенностиIP-адрес и его особенности
    Фундаментальные статьи
  • Joomla 2.5 добавление пользователями материалов (статей) на сайтJoomla 2.5 добавление пользователями материалов (статей) на сайт
    Фундаментальные статьи
  • Система поведенческого анализа антивируса простыми словамиСистема поведенческого анализа антивируса простыми словами
    Фундаментальные статьи

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

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

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

При копировании, создании, сохранении или перемещении файлов и папок в 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

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

    • В правой панели редактора реестра дважды нажмите по параметру с именем LongPathsEnabled и присвойте значение 1 вместо 0 для этого параметра.
    • Закройте редактор реестра, перезагрузите компьютер.
    • В редакторе локальной групповой политики

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

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

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

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

      Понятия «путь» и «имя файла»

      Очень часто в компьютерной литературе используются термины «путь» и «имя файла» под разными значениями. Обычно под словом «путь» понимают адрес или расположение файла, т. е. диск, папка и подпапки в которых расположен файл. Однако Microsoft и другие считают, что в путь к файлу входит не только его расположение но и само имя файла. А некоторые подразумевают под словом «путь» только имена файла и папок, в которых он расположен, без указания диска. Некоторые пользователи полагают, что «имя файла» не включает расширение. В данной статье расширение всегда является частью имени файла. На примере ниже синим цветом выделен путь к файлу, а красным имя файла.
      X:папкаподпапка файл.расширение

      Зарезервированные символы и имена

      Большинство часто употребляемых символов разрешается использовать в имени файла. Имя файла не должно содержать „” (знак меньше), „>” (знак больше), „:” (двоеточие), „ «” (двойные кавычки), „ /” (слеш), „ ” (обратный слеш), „ |” (вертикальная черта), „ ?” (вопросительный знак), „ *” (звездочка), а также не может заканчиваться точкой или пробелом. Файлы также нельзя называть зарезервированными именами устройств: CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, и LPT9.

      Ограничения на длины имен файлов и путей

      Существуют ограничения на длину имени файла и на длину пути. Абсолютное ограничение длины имени файла вместе включая путь к нему равно 260 символам. Этот предел называют термином MAX_PATH. На самом же деле на практике пределы для имен еще меньше из-за ряда других ограничений. Например, каждая строка на конце должна содержать так называемый нулевой символ, который обозначает конец строки. Несмотря на то, что маркер конца строки не отображается, он учитывается как отдельный символ при подсчете длины, а значит остается 259 символов доступных для имени файла и пути к нему. Первые три символа в пути используются для обозначения диска (например, C:). Это уменьшает предел для имен папок, подпапок и файла до 256 символов.

      На имя объекта (папки или файла) наложено ограничение длины 255 символов. Этот предел действителен только, если объект не расположен внутри папки. Так как при расположении объекта внутри папки, сумма длин всех папок в которых он расположен, разделителей и имени объекта ограничена 256 символами, то предел длины самого имени объекта меньше 255 символов.

      Давно известен тот факт, что Проводник Windows и большинство Windows-приложений не могут работать с файлами и папками, длина пути к которым превышает 260 символов. И это — лишь программное ограничение на уровне Win32 API, известное также как MAX_PATH, тогда как файловая система NTFS сама по себе допускает до 32767 символов в адресе объекта файловой системы, чем успешно пользовались сторонние приложения, работавшие в обход стандартного API, например, FAR и Total Commander.

      Также данное ограничение не касалось работы с файлами при сетевом доступе, что приводило к казусным ситуациям: рядовой пользователь в расшаренной папке может создавать и изменять файлы и папки, администратор через Windows Explorer — получает отказ доступа. Причём данное ограничение имело место не только в Windows 7/8/8.1 и более ранних ОС, но и в новейшей Windows 10.

      Для обхода ограничения применялся, в зависимости от ситуации и уровня подготовки сидящего за ПК пользователя, целый ряд различных приёмов: символические ссылки, ручное сокращение количества символов, создание виртуальных дисков и прочее.

      И вот, как сообщает ряд тестеров регулярно выпускаемых закрытых сборок Windows 10, компания Microsoft, наконец, снизошла до исправления этого недостатка и выпуска исправления. Точнее — реализации настройки, которую должен будет включить сам пользователь. В шаблонах групповых политик появился соответствующий параметр «Включение длинных адресов NTFS» (Конфигурация компьютера -> Административные шаблоны -> Система -> Файловая система -> NTFS).

      3070 Gigabyte Gaming за 50 тр с началом

      Выбираем игровой ноут: на что смотреть, на чем сэкономить

      3070 Gainward Phantom дешевле 50 тр

      13700K дешевле 40 тр в Регарде

      Ищем PHP-программиста для апгрейда конфы

      3070 дешевле 50 тр в Ситилинке

      MSI 3050 за 25 тр в Ситилинке

      3060 Gigabyte Gaming за 30 тр с началом

      13600K дешевле 30 тр в Регарде

      4080 почти за 100тр — дешевле чем по курсу 60

      12900K за 40тр с началом в Ситилинке

      RTX 4090 за 140 тр в Регарде

      Компьютеры от 10 тр в Ситилинке

      3060 Ti Gigabyte за 42 тр в Регарде

      Единственное, что огорчает — Редактор групповых политик (gpedit.msc) отсутствует в редакциях Windows 10, отличных от «Профессиональная» и «Корпоративная» (хотя существуют неофициальные и не совсем легальные способы обойти это ограничение). Впрочем, необходимые ключи в реестре наверняка будут найдены. Как подсказывает один из читателей, это параметр LongPathsEnabled (тип DWORD), расположенный в реестре по адресу HKEY_LOCAL_MACHINESystemCurrentControlSetPolicies.

      Screenshot of a Windows command shell showing filenames in a directory

      Filename list, with long filenames containing comma and space characters as they appear in a software display.

      A filename or file name is a name used to uniquely identify a computer file in a directory structure. Different file systems impose different restrictions on filename lengths.

      A filename may (depending on the file system) include:

      • name – base name of the file
      • extension (format or extension) – indicates the content of the file (e.g. .txt , .exe , .html , .COM , .c~ etc.)

      The components required to identify a file by utilities and applications varies across operating systems, as does the syntax and format for a valid filename.

      Filenames may contain any arbitrary bytes the user chooses. This may include things like a revision or generation number of the file such as computer code, a numerical sequence number (widely used by digital cameras through the DCF standard), a date and time (widely used by smartphone camera software and for screenshots), and/or a comment such as the name of a subject or a location or any other text to facilitate the searching the files. In fact, even unprintable characters, including bell, 0x00, Return and LineFeed can be part of a filename, although most utilities do not handle them well.

      Some people use of the term filename when referring to a complete specification of device, subdirectories and filename such as the Windows C:Program FilesMicrosoft GamesChessChess.exe. The filename in this case is Chess.exe. Some utilities have settings to suppress the extension as with MS Windows Explorer.

      History [ edit ]

      On early personal computers using the CP/M operating system, with the File Allocation Table (FAT) filesystem, filenames were always 11 characters. This was referred to as the 8.3 filename with a maximum of an 8 byte name and a maximum of a 3 byte extension. Utilities and applications allowed users to specify filenames without trailing spaces and include a dot before the extension. The dot was not actually stored in the directory. Using only 7 bit characters allowed several file attributes [1] to be included in the actual filename by using the high-order-bit. These attributes included Readonly, Archive, HIDDEN and SYS. Eventually this was too restrictive and the number of characters allowed increased. The attribute bits were moved to a special block of the file including additional information. This led to compatibility problems when moving files between different file systems. [2]

      During the 1970s, some mainframe and minicomputers where files on the system were identified by a user name, or account number.

      For example, on Digital Equipment Corporation RSTS/E and TOPS-10 operating systems, files were identified by

      • optional device name (one or two characters) followed by an optional unit number, and a colon «:». If not present, it was presumed to be SY:
      • the account number, consisting of a bracket «[«, a pair of numbers separated by a comma, and followed by a close bracket «]». If omitted, it was presumed to be yours.
      • mandatory file name, consisting of 1 to 6 characters (upper-case letters or digits)
      • optional 3-character extension.

      On the IBM OS/VS1, OS/390 and MVS operating systems, a file name was up to 44 characters, consisting of upper case letters, digits, and the period. A file name must start with a letter or number, a period must occur at least once each 8 characters, two consecutive periods could not appear in the name, and must end with a letter or digit. By convention, the letters and numbers before the first period was the account number of the owner or the project it belonged to, but there was no requirement to use this convention.

      On the McGill University MUSIC/SP system, file names consisted of

      • Optional account number, which was one to four characters followed by a colon.If the account number was missing, it was presumed to be in your account, but if it was not, it was presumed to be in the *COM: pseudo-account, which is where all files marked as public were catalogued.
      • 1-17 character file name, which could be upper case letters or digits, and the period, with the requirement it not begin or end with a period, or have two consecutive periods.

      The Univac VS/9 operating system had file names consisting of

      • Account name, consisting of a dollar sign «$», a 1-7 character (letter or digit) username, and a period («.»). If not present it was presumed to be in your account, but if it wasn’t, the operating system would look in the system manager’s account $TSOS. If you typed in a dollar sign only as the account, this would indicate the file was in the $TSOS account unless the first 1-7 character of the file name before the first period matched an actual account name, then that account was used, e.g. ABLE.BAKER is a file in your account, but if not there the system would search for $TSOS.ABLE.BAKER, but if $ABLE.BAKER was specified, the file $TSOS.ABLE.BAKER would be used unless $ABLE was a valid account, then it would look for a file named BAKER in that account.
      • File name, 1-56 characters (letters and digits) separated by periods. File names cannot start or end with a period, nor can two consecutive periods appear.

      In 1985, RFC 959 officially defined a pathname to be the character string that must be entered into a file system by a user in order to identify a file. [3]

      Around 1995, VFAT, an extension to the MS-DOS FAT filesystem, was introduced in Windows 95 and Windows NT. It allowed mixed-case Unicode long filenames (LFNs), in addition to classic «8.3» names.

      References: absolute vs relative [ edit ]

      An absolute reference includes all directory levels. In some systems, a filename reference that does not include the complete directory path defaults to the current working directory. This is a relative reference. One advantage of using a relative reference in program configuration files or scripts is that different instances of the script or program can use different files.

      This makes an absolute or relative path composed of a sequence of filenames.

      Number of names per file [ edit ]

      Unix-like file systems allow a file to have more than one name; in traditional Unix-style file systems, the names are hard links to the file’s inode or equivalent. Windows supports hard links on NTFS file systems, and provides the command fsutil in Windows XP, and mklink in later versions, for creating them. [4] [5] Hard links are different from Windows shortcuts, classic Mac OS/macOS aliases, or symbolic links. The introduction of LFNs with VFAT allowed filename aliases. For example, longfi~1. with a maximum of eight plus three characters was a filename alias of « long file name. » as a way to conform to 8.3 limitations for older programs.

      This property was used by the move command algorithm that first creates a second filename and then only removes the first filename.

      Other filesystems, by design, provide only one filename per file, which guarantees that alteration of one filename’s file does not alter the other filename’s file.

      Length restrictions [ edit ]

      Some filesystems restrict the length of filenames. In some cases, these lengths apply to the entire file name, as in 44 characters on IBM S/370. [6] In other cases, the length limits may apply to particular portions of the filename, such as the name of a file in a directory, or a directory name. For example, 9 (e.g., 8-bit FAT in Standalone Disk BASIC), 11 (e.g. FAT12, FAT16, FAT32 in DOS), 14 (e.g. early Unix), 21 (Human68K), 31, 30 (e.g. Apple DOS 3.2 and 3.3), 15 (e.g. Apple ProDOS), 44 (e.g. IBM S/370), [6] or 255 (e.g. early Berkeley Unix) characters or bytes. Length limits often result from assigning fixed space in a filesystem to storing components of names, so increasing limits often requires an incompatible change, as well as reserving more space.

      A particular issue with filesystems that store information in nested directories is that it may be possible to create a file with a complete pathname that exceeds implementation limits, since length checking may apply only to individual parts of the name rather than the entire name. Many Windows applications are limited to a MAX_PATH value of 260, but Windows file names can easily exceed this limit [1]. From Windows 10, version 1607, MAX_PATH limitations have been removed. [7]

      Filename extensions [ edit ]

      Many file systems, including FAT, NTFS, and VMS systems, consider as filename extension the part of the file name that consists of one or more characters following the last period in the filename, dividing the filename into two parts: a base name or stem and an extension or suffix used by some applications to indicate the file type. Multiple output files created by an application use the same basename and various extensions. For example, a compiler might use the extension FOR for source input file (for Fortran code), OBJ for the object output and LST for the listing. Although there are some common extensions, they are arbitrary and a different application might use REL and RPT . Extensions have been restricted, at least historically on some systems, to a length of 3 characters, but in general can have any length, e.g., html .

      Encoding interoperability [ edit ]

      There is no general encoding standard for filenames.

      File names have to be exchanged between software environments for network file transfer, file system storage, backup and file synchronization software, configuration management, data compression and archiving, etc. It is thus very important not to lose file name information between applications. This led to wide adoption of Unicode as a standard for encoding file names, although legacy software might not be Unicode-aware.

      Encoding indication interoperability [ edit ]

      Traditionally, filenames allowed any character in their filenames as long as they were file system safe. [2] Although this permitted the use of any encoding, and thus allowed the representation of any local text on any local system, it caused many interoperability issues.

      A filename could be stored using different byte strings in distinct systems within a single country, such as if one used Japanese Shift JIS encoding and another Japanese EUC encoding. Conversion was not possible as most systems did not expose a description of the encoding used for a filename as part of the extended file information. This forced costly filename encoding guessing with each file access. [2]

      A solution was to adopt Unicode as the encoding for filenames.

      In the classic Mac OS, however, encoding of the filename was stored with the filename attributes. [2]

      Unicode interoperability [ edit ]

      The Unicode standard solves the encoding determination issue.

      Nonetheless, some limited interoperability issues remain, such as normalization (equivalence), or the Unicode version in use. For instance, UDF is limited to Unicode 2.0; macOS’s HFS+ file system applies NFD Unicode normalization and is optionally case-sensitive (case-insensitive by default.) Filename maximum length is not standard and might depend on the code unit size. Although it is a serious issue, in most cases this is a limited one. [2]

      On Linux, this means the filename is not enough to open a file: additionally, the exact byte representation of the filename on the storage device is needed. This can be solved at the application level, with some tricky normalization calls. [8]

      The issue of Unicode equivalence is known as «normalized-name collision». A solution is the Non-normalizing Unicode Composition Awareness used in the Subversion and Apache technical communities. [9] This solution does not normalize paths in the repository. Paths are only normalized for the purpose of comparisons. Nonetheless, some communities have patented this strategy, forbidding its use by other communities. [ clarification needed ]

      Perspectives [ edit ]

      To limit interoperability issues, some ideas described by Sun are to:

      • use one Unicode encoding (such as UTF-8)
      • do transparent code conversions on filenames
      • store no normalized filenames
      • check for canonical equivalence among filenames, to avoid two canonically equivalent filenames in the same directory. [2]

      Those considerations create a limitation not allowing a switch to a future encoding different from UTF-8.

      Unicode migration [ edit ]

      One issue was migration to Unicode.
      For this purpose, several software companies provided software for migrating filenames to the new Unicode encoding.

      • Microsoft provided migration transparent for the user throughout the VFAT technology
      • Apple provided «File Name Encoding Repair Utility v1.0». [10]
      • The Linux community provided “convmv”. [11]

      Mac OS X 10.3 marked Apple’s adoption of Unicode 3.2 character decomposition, superseding the Unicode 2.1 decomposition used previously. This change caused problems for developers writing software for Mac OS X. [12]

      Uniqueness [ edit ]

      Within a single directory, filenames must be unique. Since the filename syntax also applies for directories, it is not possible to create a file and directory entries with the same name in a single directory. Multiple files in different directories may have the same name.

      Uniqueness approach may differ both on the case sensitivity and on the Unicode normalization form such as NFC, NFD.
      This means two separate files might be created with the same text filename and a different byte implementation of the filename, such as L»x00C0.txt» (UTF-16, NFC) (Latin capital A with grave) and L»x0041x0300.txt» (UTF-16, NFD) (Latin capital A, grave combining). [13]

      Letter case preservation [ edit ]

      Some filesystems, such as FAT, store filenames as upper-case regardless of the letter case used to create them. For example, a file created with the name «MyName.Txt» or «myname.txt» would be stored with the filename «MYNAME.TXT». Any variation of upper and lower case can be used to refer to the same file. These kinds of file systems are called case-insensitive and are not case-preserving. Some filesystems prohibit the use of lower case letters in filenames altogether.

      Some file systems store filenames in the form that they were originally created; these are referred to as case-retentive or case-preserving. Such a file system can be case-sensitive or case-insensitive. If case-sensitive, then «MyName.Txt» and «myname.txt» may refer to two different files in the same directory, and each file must be referenced by the exact capitalization by which it is named. On a case-insensitive, case-preserving file system, on the other hand, only one of «MyName.Txt», «myname.txt» and «Myname.TXT» can be the name of a file in a given directory at a given time, and a file with one of these names can be referenced by any capitalization of the name.

      From its original inception, Unix and its derivative systems were case-preserving. However, not all Unix-like file systems are case-sensitive; by default, HFS+ in macOS is case-insensitive, and SMB servers usually provide case-insensitive behavior (even when the underlying file system is case-sensitive, e.g. Samba on most Unix-like systems), and SMB client file systems provide case-insensitive behavior. File system case sensitivity is a considerable challenge for software such as Samba and Wine, which must interoperate efficiently with both systems that treat uppercase and lowercase files as different and with systems that treat them the same. [14]

      Reserved characters and words [ edit ]

      File systems have not always provided the same character set for composing a filename. Before Unicode became a de facto standard, file systems mostly used a locale-dependent character set. By contrast, some new systems permit a filename to be composed of almost any character of the Unicode repertoire, and even some non-Unicode byte sequences. Limitations may be imposed by the file system, operating system, application, or requirements for interoperability with other systems.

      Many file system utilities prohibit control characters from appearing in filenames. In Unix-like file systems, the null character [15] and the path separator / are prohibited.

      In Windows [ edit ]

      File system utilities and naming conventions on various systems prohibit particular characters from appearing in filenames or make them problematic: [16]

      Character Name Reason for prohibition
      / slash Used as a path name component separator in Unix-like, Windows, and Amiga systems. (For as long as the SwitChar setting is set to ‘/ ’, the DOS COMMAND.COM shell would consume it as a switch character, but DOS and Windows themselves always accept it as a separator on API level.)
      The big solidus ⧸ (Unicode code point U+29F8) is permitted in Windows filenames.
      backslash Used as the default path name component separator in DOS, OS/2 and Windows (even if the SwitChar is set to ‘-‘; allowed in Unix filenames, see Note 1).
      The big reverse solidus ⧹ (U+29F9) is permitted in Windows filenames.
      ? question mark Used as a wildcard in Unix, Windows and AmigaOS; marks a single character. Allowed in Unix filenames, see Note 1.
      The glottal stop ʔ (U+0294), the interrobang ‽ (U+203D), the inverted question mark ¿ (U+00BF) and the double question mark ⁇ (U+2047) are allowed in all filenames.
      % percent Used as a wildcard in RT-11; marks a single character. Not special on Windows.
      * asterisk
      or star
      Used as a wildcard in Unix, DOS, RT-11, VMS and Windows. Marks any sequence of characters (Unix, Windows, DOS) or any sequence of characters in either the basename or extension (thus «*.*» in DOS means «all files». Allowed in Unix filenames, see Note 1.
      See Star (glyph) for many asterisk-like characters allowed in filenames.
      : colon Used to determine the mount point / drive on Windows; used to determine the virtual device or physical device such as a drive on AmigaOS, RT-11 and VMS; used as a pathname separator in classic Mac OS. Doubled after a name on VMS, indicates the DECnet nodename (equivalent to a NetBIOS (Windows networking) hostname preceded by «\».). Colon is also used in Windows to separate an alternative data stream from the main file.
      The letter colon ꞉ (U+A789) and the ratio symbol ∶ (U+2236) are permitted in Windows filenames. In the Segoe UI font, used in Windows Explorer, the glyphs for the colon and the letter colon are identical.
      | vertical bar
      or pipe
      Designates software pipelining in Unix, DOS and Windows; allowed in Unix filenames, see Note 1. The mathematical operator ∣ (U+2223) is permitted in Windows filenames.
      « straight double quote A legacy restriction carried over from DOS. The single quotes ‘ (U+0027), ‘ (U+2018), and ’ (U+2019) and the curved double quotes “ (U+201C) and ” (U+201D) are permitted anywhere in filenames. See Note 1.
      less than Used to redirect input, allowed in Unix filenames, see Note 1. The spacing modifier letter ˂ (U+2C2) is permitted in Windows filenames.
      > greater than Used to redirect output, allowed in Unix filenames, see Note 1. The spacing modifier letter ˃ (U+2C3) is permitted in Windows filenames.
      . period
      or dot
      Folder names cannot end with a period in Windows, though the name can end with a period followed by a whitespace character such as a non-breaking space. Elsewhere, the period is allowed, but the last occurrence will be interpreted to be the extension separator in VMS, DOS, and Windows. In other OSes, usually considered as part of the filename, and more than one period (full stop) may be allowed. In Unix, a leading period means the file or folder is normally hidden.
      , comma Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
      ; semicolon Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
      = equals sign Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
      space Allowed, but the space is also used as a parameter separator in command line applications. This can be solved by quoting the entire filename.

      Note 1: While they are allowed in Unix file and folder names, most Unix shells require specific characters such as spaces, , |, , and sometimes :, (, ), &, ;, #, as well as wildcards such as ? and *, to be quoted or escaped:

      The character å ( 0xE5 ) was not allowed as the first letter in a filename under 86-DOS and MS-DOS/PC DOS 1.x-2.x, but can be used in later versions.

      In Windows utilities, the space and the period are not allowed as the final character of a filename. [17] The period is allowed as the first character, but some Windows applications, such as Windows Explorer, forbid creating or renaming such files (despite this convention being used in Unix-like systems to describe hidden files and directories). Workarounds include appending a dot when renaming the file (that is then automatically removed afterwards), using alternative file managers, creating the file using the command line, or saving a file with the desired filename from within an application. [18]

      Some file systems on a given operating system (especially file systems originally implemented on other operating systems), and particular applications on that operating system, may apply further restrictions and interpretations. See comparison of file systems for more details on restrictions.

      In Unix-like systems, DOS, and Windows, the filenames «.» and «..» have special meanings (current and parent directory respectively). Windows 95/98/ME also uses names like «…», «….» and so on to denote grandparent or great-grandparent directories. [19] All Windows versions forbid creation of filenames that consist of only dots, although names consist of three dots («…») or more are legal in Unix.

      In addition, in Windows and DOS utilities, some words are also reserved and cannot be used as filenames. [18] For example, DOS device files: [20]

      CON, PRN, AUX, CLOCK$, NUL COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9[21] LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9[21] LST (only in 86-DOS and DOS 1.xx) KEYBD$, SCREEN$ (only in multitasking MS-DOS 4.0) $IDLE$ (only in Concurrent DOS 386, Multiuser DOS and DR DOS 5.0 and higher) CONFIG$ (only in MS-DOS 7.0-8.0)

      Systems that have these restrictions cause incompatibilities with some other filesystems. For example, Windows will fail to handle, or raise error reports for, these legal UNIX filenames: aux.c, [22] q»uote»s.txt, or NUL.txt.

      NTFS filenames that are used internally include:

      $Mft, $MftMirr, $LogFile, $Volume, $AttrDef, $Bitmap, $Boot, $BadClus, $Secure, $Upcase, $Extend, $Quota, $ObjId and $Reparse

      Comparison of filename limitations [ edit ]

      System Case
      sensitive
      Case
      preserving
      Allowed character set Reserved characters Reserved words Maximum length (characters) Comments
      8-bit FAT ? ? 7-bit ASCII (but stored as bytes) first character not allowed to be 0x00 or 0xFF 9 Maximum 9 character base name limit for sequential files (without extension), or maximum 6 and 3 character extension for binary files; see 6.3 filename
      FAT12, FAT16, FAT32 No No any SBCS/DBCS OEM codepage 0x00-0x1F 0x7F » * / : < >? | + , . ; = [ ] (in some environments also: ! @ ; DOS 1/2 did not allow 0xE5 as first character) Device names including: $IDLE$ AUX COM1…COM4 CON CONFIG$ CLOCK$ KEYBD$ LPT1…LPT4 LST NUL PRN SCREEN$ (depending on AVAILDEV status everywhere or only in virtual DEV directory) 11 Maximum 8 character base name limit and 3 character extension; see 8.3 filename
      VFAT No Yes Unicode, using UCS-2 encoding 0x00-0x1F 0x7F » * / : < >? | 255
      exFAT No Yes Unicode, using UTF-16 encoding 0x00-0x1F 0x7F » * / : < >? | 255
      NTFS Optional Yes Unicode, using UTF-16 encoding 0x00-0x1F 0x7F » * / : < >? | Only in root directory: $AttrDef $BadClus $Bitmap $Boot $LogFile $MFT $MFTMirr pagefile.sys $Secure $UpCase $Volume $Extend $Extend$ObjId $Extend$Quota $Extend$Reparse ($Extend is a directory) 255 Paths can be up to 32,000 characters.

      Forbids the use of characters in range 1-31 (0x01-0x1F) and characters » * / : < >? | unless the name is flagged as being in the Posix namespace. NTFS allows each path component (directory or filename) to be 255 characters long [ dubious – discuss ] .

      Windows forbids the use of the MS-DOS device names AUX, CLOCK$, COM0, …, COM9, CON, LPT0, …, LPT9, NUL and PRN, as well as these names with any extension (for example, AUX.txt), except when using Long UNC paths (ex. \.C:nul.txt or \?D:auxcon). (CLOCK$ may be used, if an extension is provided.) The Win32 API strips trailing period (full-stop), and leading and trailing space characters from filenames, except when UNC paths are used. These restrictions only apply to Windows; in Linux distributions that support NTFS, filenames are written using NTFS’s Posix namespace, which allows any Unicode character except / and NUL.

      «Qualified» contains . after every 8 characters or fewer. [23] Partitioned data sets (PDS or PDSE) are divided into members with names of up to 8 characters; the member name is placed in parenthesises after the name of the PDS, e.g. PAYROLL.DEV.CBL(PROG001)

      See also [ edit ]

      • File system
      • Fully qualified file name
      • Long filename
      • Path (computing)
      • Slug (Web publishing)
      • Symbolic link
      • Uniform Resource Identifier (URI)
      • Uniform Resource Locator (URL) and Internationalized resource identifier
      • Windows (Win32) File Naming Conventions (Filesystem Agnostic)

      References [ edit ]

      1. ^ «CPM — CP/M disk and file system format».
      2. ^ abcdef David Robinson; Ienup Sung; Nicolas Williams (March 2006). «Solaris presentations: File Systems, Unicode, and Normalization» (PDF) . San Francisco: Sun.com. Archived from the original (PDF) on July 4, 2012.
      3. ^ RFC 959 IETF.org RFC 959, File Transfer Protocol (FTP)
      4. ^ «Fsutil command description page». Microsoft.com . Retrieved September 15, 2013 .
      5. ^ «NTFS Hard Links, Directory Junctions, and Windows Shortcuts». Flex hex. Inv Softworks . Retrieved March 12, 2011 .
      6. ^ ab «ddname support with FTP, z/OS V1R11.0 Communications Server IP User’s Guide and Commands z/OS V1R10.0-V1R11.0 SC31-8780-09». IBM.com.
      7. ^ «Maximum Path Length Limitation — Win32 apps».
      8. ^ «Filenames with accents». Ned Batchelder. June 2011 . Retrieved September 17, 2013 .
      9. ^ «NonNormalizingUnicodeCompositionAwareness — Subversion Wiki». Wiki.apache.org. January 21, 2013 . Retrieved September 17, 2013 .
      10. ^ «File Name Encoding Repair Utility v1.0». Support.apple.com. June 1, 2006 . Retrieved October 2, 2018 .
      11. ^ «convmv — converts filenames from one encoding to another». J3e.de . Retrieved September 17, 2013 .
      12. ^ «Re: git on MacOSX and files with decomposed utf-8 file names». KernelTrap. May 7, 2010. Archived from the original on March 15, 2011 . Retrieved July 5, 2010 .
      13. ^ «Cross platform filepath naming conventions — General Programming». GameDev.net . Retrieved September 17, 2013 .
      14. ^ «CaseInsensitiveFilenames — The Official Wine Wiki». Wiki.winehq.org. November 8, 2009. Archived from the original on August 18, 2010 . Retrieved August 20, 2010 .
      15. ^ «The Open Group Base Specifications Issue 6». IEEE Std 1003.1-2001. The Open Group. 2001.
      16. ^ «Naming Files, Paths, and Namespaces (Windows)». Msdn.microsoft.com. August 26, 2013 . Retrieved September 17, 2013 .
      17. ^ «Windows Naming Conventions». MSDN, Microsoft.com. See last bulleted item.
      18. ^ ab Naming a file msdn.microsoft.com (MSDN), filename restrictions on Windows
      19. ^Microsoft Windows 95 README for Tips and Tricks, Microsoft , retrieved August 27, 2015
      20. ^MS-DOS Device Driver Names Cannot be Used as File Names., Microsoft
      21. ^ abNaming Files, Paths, and Namespaces, Microsoft
      22. ^ Ritter, Gunnar (January 30, 2007). «The tale of «aux.c» «. Heirloom Project.
      23. ^ «Subparameter Definition, z/OS V1R11.0 MVS JCL Reference». IBM.com . Retrieved September 17, 2013 .
      24. ^ Lewine, Donald. POSIX Programmer’s Guide: Writing Portable UNIX Programs 1991 O’Reilly & Associates, Inc. Sebastopol, CA pp63-64
      25. ^ pathchk — check pathnames
      26. ^ Hewlett-Packard Company Roseville, CA HP 250 Syntax Reference Rev 1/84 Manual Part no 45260-90063

      External links [ edit ]

      • Data Formats Filename at Curlie
      • File Extension Library
      • FILExt
      • WikiExt — File Extensions Encyclopedia
      • Naming Files, Paths, and Namespaces (MSDN)
      • 2009 POSIX portable filename character set
      • Standard ECMA-208, December 1994, System-Independent Data Format
      • Best Practices for File Naming, USA: Stanford University Libraries, Data Management Services

      Screenshot of a Windows command shell showing filenames in a directory

      Filename list, with long filenames containing comma and space characters as they appear in a software display.

      A filename or file name is a name used to uniquely identify a computer file in a directory structure. Different file systems impose different restrictions on filename lengths.

      A filename may (depending on the file system) include:

      • name – base name of the file
      • extension (format or extension) – indicates the content of the file (e.g. .txt , .exe , .html , .COM , .c~ etc.)

      The components required to identify a file by utilities and applications varies across operating systems, as does the syntax and format for a valid filename.

      Filenames may contain any arbitrary bytes the user chooses. This may include things like a revision or generation number of the file such as computer code, a numerical sequence number (widely used by digital cameras through the DCF standard), a date and time (widely used by smartphone camera software and for screenshots), and/or a comment such as the name of a subject or a location or any other text to facilitate the searching the files. In fact, even unprintable characters, including bell, 0x00, Return and LineFeed can be part of a filename, although most utilities do not handle them well.

      Some people use of the term filename when referring to a complete specification of device, subdirectories and filename such as the Windows C:Program FilesMicrosoft GamesChessChess.exe. The filename in this case is Chess.exe. Some utilities have settings to suppress the extension as with MS Windows Explorer.

      History [ edit ]

      On early personal computers using the CP/M operating system, with the File Allocation Table (FAT) filesystem, filenames were always 11 characters. This was referred to as the 8.3 filename with a maximum of an 8 byte name and a maximum of a 3 byte extension. Utilities and applications allowed users to specify filenames without trailing spaces and include a dot before the extension. The dot was not actually stored in the directory. Using only 7 bit characters allowed several file attributes [1] to be included in the actual filename by using the high-order-bit. These attributes included Readonly, Archive, HIDDEN and SYS. Eventually this was too restrictive and the number of characters allowed increased. The attribute bits were moved to a special block of the file including additional information. This led to compatibility problems when moving files between different file systems. [2]

      During the 1970s, some mainframe and minicomputers where files on the system were identified by a user name, or account number.

      For example, on Digital Equipment Corporation RSTS/E and TOPS-10 operating systems, files were identified by

      • optional device name (one or two characters) followed by an optional unit number, and a colon «:». If not present, it was presumed to be SY:
      • the account number, consisting of a bracket «[«, a pair of numbers separated by a comma, and followed by a close bracket «]». If omitted, it was presumed to be yours.
      • mandatory file name, consisting of 1 to 6 characters (upper-case letters or digits)
      • optional 3-character extension.

      On the IBM OS/VS1, OS/390 and MVS operating systems, a file name was up to 44 characters, consisting of upper case letters, digits, and the period. A file name must start with a letter or number, a period must occur at least once each 8 characters, two consecutive periods could not appear in the name, and must end with a letter or digit. By convention, the letters and numbers before the first period was the account number of the owner or the project it belonged to, but there was no requirement to use this convention.

      On the McGill University MUSIC/SP system, file names consisted of

      • Optional account number, which was one to four characters followed by a colon.If the account number was missing, it was presumed to be in your account, but if it was not, it was presumed to be in the *COM: pseudo-account, which is where all files marked as public were catalogued.
      • 1-17 character file name, which could be upper case letters or digits, and the period, with the requirement it not begin or end with a period, or have two consecutive periods.

      The Univac VS/9 operating system had file names consisting of

      • Account name, consisting of a dollar sign «$», a 1-7 character (letter or digit) username, and a period («.»). If not present it was presumed to be in your account, but if it wasn’t, the operating system would look in the system manager’s account $TSOS. If you typed in a dollar sign only as the account, this would indicate the file was in the $TSOS account unless the first 1-7 character of the file name before the first period matched an actual account name, then that account was used, e.g. ABLE.BAKER is a file in your account, but if not there the system would search for $TSOS.ABLE.BAKER, but if $ABLE.BAKER was specified, the file $TSOS.ABLE.BAKER would be used unless $ABLE was a valid account, then it would look for a file named BAKER in that account.
      • File name, 1-56 characters (letters and digits) separated by periods. File names cannot start or end with a period, nor can two consecutive periods appear.

      In 1985, RFC 959 officially defined a pathname to be the character string that must be entered into a file system by a user in order to identify a file. [3]

      Around 1995, VFAT, an extension to the MS-DOS FAT filesystem, was introduced in Windows 95 and Windows NT. It allowed mixed-case Unicode long filenames (LFNs), in addition to classic «8.3» names.

      References: absolute vs relative [ edit ]

      An absolute reference includes all directory levels. In some systems, a filename reference that does not include the complete directory path defaults to the current working directory. This is a relative reference. One advantage of using a relative reference in program configuration files or scripts is that different instances of the script or program can use different files.

      This makes an absolute or relative path composed of a sequence of filenames.

      Number of names per file [ edit ]

      Unix-like file systems allow a file to have more than one name; in traditional Unix-style file systems, the names are hard links to the file’s inode or equivalent. Windows supports hard links on NTFS file systems, and provides the command fsutil in Windows XP, and mklink in later versions, for creating them. [4] [5] Hard links are different from Windows shortcuts, classic Mac OS/macOS aliases, or symbolic links. The introduction of LFNs with VFAT allowed filename aliases. For example, longfi~1. with a maximum of eight plus three characters was a filename alias of « long file name. » as a way to conform to 8.3 limitations for older programs.

      This property was used by the move command algorithm that first creates a second filename and then only removes the first filename.

      Other filesystems, by design, provide only one filename per file, which guarantees that alteration of one filename’s file does not alter the other filename’s file.

      Length restrictions [ edit ]

      Some filesystems restrict the length of filenames. In some cases, these lengths apply to the entire file name, as in 44 characters on IBM S/370. [6] In other cases, the length limits may apply to particular portions of the filename, such as the name of a file in a directory, or a directory name. For example, 9 (e.g., 8-bit FAT in Standalone Disk BASIC), 11 (e.g. FAT12, FAT16, FAT32 in DOS), 14 (e.g. early Unix), 21 (Human68K), 31, 30 (e.g. Apple DOS 3.2 and 3.3), 15 (e.g. Apple ProDOS), 44 (e.g. IBM S/370), [6] or 255 (e.g. early Berkeley Unix) characters or bytes. Length limits often result from assigning fixed space in a filesystem to storing components of names, so increasing limits often requires an incompatible change, as well as reserving more space.

      A particular issue with filesystems that store information in nested directories is that it may be possible to create a file with a complete pathname that exceeds implementation limits, since length checking may apply only to individual parts of the name rather than the entire name. Many Windows applications are limited to a MAX_PATH value of 260, but Windows file names can easily exceed this limit [1]. From Windows 10, version 1607, MAX_PATH limitations have been removed. [7]

      Filename extensions [ edit ]

      Many file systems, including FAT, NTFS, and VMS systems, consider as filename extension the part of the file name that consists of one or more characters following the last period in the filename, dividing the filename into two parts: a base name or stem and an extension or suffix used by some applications to indicate the file type. Multiple output files created by an application use the same basename and various extensions. For example, a compiler might use the extension FOR for source input file (for Fortran code), OBJ for the object output and LST for the listing. Although there are some common extensions, they are arbitrary and a different application might use REL and RPT . Extensions have been restricted, at least historically on some systems, to a length of 3 characters, but in general can have any length, e.g., html .

      Encoding interoperability [ edit ]

      There is no general encoding standard for filenames.

      File names have to be exchanged between software environments for network file transfer, file system storage, backup and file synchronization software, configuration management, data compression and archiving, etc. It is thus very important not to lose file name information between applications. This led to wide adoption of Unicode as a standard for encoding file names, although legacy software might not be Unicode-aware.

      Encoding indication interoperability [ edit ]

      Traditionally, filenames allowed any character in their filenames as long as they were file system safe. [2] Although this permitted the use of any encoding, and thus allowed the representation of any local text on any local system, it caused many interoperability issues.

      A filename could be stored using different byte strings in distinct systems within a single country, such as if one used Japanese Shift JIS encoding and another Japanese EUC encoding. Conversion was not possible as most systems did not expose a description of the encoding used for a filename as part of the extended file information. This forced costly filename encoding guessing with each file access. [2]

      A solution was to adopt Unicode as the encoding for filenames.

      In the classic Mac OS, however, encoding of the filename was stored with the filename attributes. [2]

      Unicode interoperability [ edit ]

      The Unicode standard solves the encoding determination issue.

      Nonetheless, some limited interoperability issues remain, such as normalization (equivalence), or the Unicode version in use. For instance, UDF is limited to Unicode 2.0; macOS’s HFS+ file system applies NFD Unicode normalization and is optionally case-sensitive (case-insensitive by default.) Filename maximum length is not standard and might depend on the code unit size. Although it is a serious issue, in most cases this is a limited one. [2]

      On Linux, this means the filename is not enough to open a file: additionally, the exact byte representation of the filename on the storage device is needed. This can be solved at the application level, with some tricky normalization calls. [8]

      The issue of Unicode equivalence is known as «normalized-name collision». A solution is the Non-normalizing Unicode Composition Awareness used in the Subversion and Apache technical communities. [9] This solution does not normalize paths in the repository. Paths are only normalized for the purpose of comparisons. Nonetheless, some communities have patented this strategy, forbidding its use by other communities. [ clarification needed ]

      Perspectives [ edit ]

      To limit interoperability issues, some ideas described by Sun are to:

      • use one Unicode encoding (such as UTF-8)
      • do transparent code conversions on filenames
      • store no normalized filenames
      • check for canonical equivalence among filenames, to avoid two canonically equivalent filenames in the same directory. [2]

      Those considerations create a limitation not allowing a switch to a future encoding different from UTF-8.

      Unicode migration [ edit ]

      One issue was migration to Unicode.
      For this purpose, several software companies provided software for migrating filenames to the new Unicode encoding.

      • Microsoft provided migration transparent for the user throughout the VFAT technology
      • Apple provided «File Name Encoding Repair Utility v1.0». [10]
      • The Linux community provided “convmv”. [11]

      Mac OS X 10.3 marked Apple’s adoption of Unicode 3.2 character decomposition, superseding the Unicode 2.1 decomposition used previously. This change caused problems for developers writing software for Mac OS X. [12]

      Uniqueness [ edit ]

      Within a single directory, filenames must be unique. Since the filename syntax also applies for directories, it is not possible to create a file and directory entries with the same name in a single directory. Multiple files in different directories may have the same name.

      Uniqueness approach may differ both on the case sensitivity and on the Unicode normalization form such as NFC, NFD.
      This means two separate files might be created with the same text filename and a different byte implementation of the filename, such as L»x00C0.txt» (UTF-16, NFC) (Latin capital A with grave) and L»x0041x0300.txt» (UTF-16, NFD) (Latin capital A, grave combining). [13]

      Letter case preservation [ edit ]

      Some filesystems, such as FAT, store filenames as upper-case regardless of the letter case used to create them. For example, a file created with the name «MyName.Txt» or «myname.txt» would be stored with the filename «MYNAME.TXT». Any variation of upper and lower case can be used to refer to the same file. These kinds of file systems are called case-insensitive and are not case-preserving. Some filesystems prohibit the use of lower case letters in filenames altogether.

      Some file systems store filenames in the form that they were originally created; these are referred to as case-retentive or case-preserving. Such a file system can be case-sensitive or case-insensitive. If case-sensitive, then «MyName.Txt» and «myname.txt» may refer to two different files in the same directory, and each file must be referenced by the exact capitalization by which it is named. On a case-insensitive, case-preserving file system, on the other hand, only one of «MyName.Txt», «myname.txt» and «Myname.TXT» can be the name of a file in a given directory at a given time, and a file with one of these names can be referenced by any capitalization of the name.

      From its original inception, Unix and its derivative systems were case-preserving. However, not all Unix-like file systems are case-sensitive; by default, HFS+ in macOS is case-insensitive, and SMB servers usually provide case-insensitive behavior (even when the underlying file system is case-sensitive, e.g. Samba on most Unix-like systems), and SMB client file systems provide case-insensitive behavior. File system case sensitivity is a considerable challenge for software such as Samba and Wine, which must interoperate efficiently with both systems that treat uppercase and lowercase files as different and with systems that treat them the same. [14]

      Reserved characters and words [ edit ]

      File systems have not always provided the same character set for composing a filename. Before Unicode became a de facto standard, file systems mostly used a locale-dependent character set. By contrast, some new systems permit a filename to be composed of almost any character of the Unicode repertoire, and even some non-Unicode byte sequences. Limitations may be imposed by the file system, operating system, application, or requirements for interoperability with other systems.

      Many file system utilities prohibit control characters from appearing in filenames. In Unix-like file systems, the null character [15] and the path separator / are prohibited.

      In Windows [ edit ]

      File system utilities and naming conventions on various systems prohibit particular characters from appearing in filenames or make them problematic: [16]

      Character Name Reason for prohibition
      / slash Used as a path name component separator in Unix-like, Windows, and Amiga systems. (For as long as the SwitChar setting is set to ‘/ ’, the DOS COMMAND.COM shell would consume it as a switch character, but DOS and Windows themselves always accept it as a separator on API level.)
      The big solidus ⧸ (Unicode code point U+29F8) is permitted in Windows filenames.
      backslash Used as the default path name component separator in DOS, OS/2 and Windows (even if the SwitChar is set to ‘-‘; allowed in Unix filenames, see Note 1).
      The big reverse solidus ⧹ (U+29F9) is permitted in Windows filenames.
      ? question mark Used as a wildcard in Unix, Windows and AmigaOS; marks a single character. Allowed in Unix filenames, see Note 1.
      The glottal stop ʔ (U+0294), the interrobang ‽ (U+203D), the inverted question mark ¿ (U+00BF) and the double question mark ⁇ (U+2047) are allowed in all filenames.
      % percent Used as a wildcard in RT-11; marks a single character. Not special on Windows.
      * asterisk
      or star
      Used as a wildcard in Unix, DOS, RT-11, VMS and Windows. Marks any sequence of characters (Unix, Windows, DOS) or any sequence of characters in either the basename or extension (thus «*.*» in DOS means «all files». Allowed in Unix filenames, see Note 1.
      See Star (glyph) for many asterisk-like characters allowed in filenames.
      : colon Used to determine the mount point / drive on Windows; used to determine the virtual device or physical device such as a drive on AmigaOS, RT-11 and VMS; used as a pathname separator in classic Mac OS. Doubled after a name on VMS, indicates the DECnet nodename (equivalent to a NetBIOS (Windows networking) hostname preceded by «\».). Colon is also used in Windows to separate an alternative data stream from the main file.
      The letter colon ꞉ (U+A789) and the ratio symbol ∶ (U+2236) are permitted in Windows filenames. In the Segoe UI font, used in Windows Explorer, the glyphs for the colon and the letter colon are identical.
      | vertical bar
      or pipe
      Designates software pipelining in Unix, DOS and Windows; allowed in Unix filenames, see Note 1. The mathematical operator ∣ (U+2223) is permitted in Windows filenames.
      « straight double quote A legacy restriction carried over from DOS. The single quotes ‘ (U+0027), ‘ (U+2018), and ’ (U+2019) and the curved double quotes “ (U+201C) and ” (U+201D) are permitted anywhere in filenames. See Note 1.
      less than Used to redirect input, allowed in Unix filenames, see Note 1. The spacing modifier letter ˂ (U+2C2) is permitted in Windows filenames.
      > greater than Used to redirect output, allowed in Unix filenames, see Note 1. The spacing modifier letter ˃ (U+2C3) is permitted in Windows filenames.
      . period
      or dot
      Folder names cannot end with a period in Windows, though the name can end with a period followed by a whitespace character such as a non-breaking space. Elsewhere, the period is allowed, but the last occurrence will be interpreted to be the extension separator in VMS, DOS, and Windows. In other OSes, usually considered as part of the filename, and more than one period (full stop) may be allowed. In Unix, a leading period means the file or folder is normally hidden.
      , comma Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
      ; semicolon Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
      = equals sign Allowed, but treated as separator by the command line interpreters COMMAND.COM and CMD.EXE on DOS and Windows.
      space Allowed, but the space is also used as a parameter separator in command line applications. This can be solved by quoting the entire filename.

      Note 1: While they are allowed in Unix file and folder names, most Unix shells require specific characters such as spaces, , |, , and sometimes :, (, ), &, ;, #, as well as wildcards such as ? and *, to be quoted or escaped:

      The character å ( 0xE5 ) was not allowed as the first letter in a filename under 86-DOS and MS-DOS/PC DOS 1.x-2.x, but can be used in later versions.

      In Windows utilities, the space and the period are not allowed as the final character of a filename. [17] The period is allowed as the first character, but some Windows applications, such as Windows Explorer, forbid creating or renaming such files (despite this convention being used in Unix-like systems to describe hidden files and directories). Workarounds include appending a dot when renaming the file (that is then automatically removed afterwards), using alternative file managers, creating the file using the command line, or saving a file with the desired filename from within an application. [18]

      Some file systems on a given operating system (especially file systems originally implemented on other operating systems), and particular applications on that operating system, may apply further restrictions and interpretations. See comparison of file systems for more details on restrictions.

      In Unix-like systems, DOS, and Windows, the filenames «.» and «..» have special meanings (current and parent directory respectively). Windows 95/98/ME also uses names like «…», «….» and so on to denote grandparent or great-grandparent directories. [19] All Windows versions forbid creation of filenames that consist of only dots, although names consist of three dots («…») or more are legal in Unix.

      In addition, in Windows and DOS utilities, some words are also reserved and cannot be used as filenames. [18] For example, DOS device files: [20]

      CON, PRN, AUX, CLOCK$, NUL COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9[21] LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9[21] LST (only in 86-DOS and DOS 1.xx) KEYBD$, SCREEN$ (only in multitasking MS-DOS 4.0) $IDLE$ (only in Concurrent DOS 386, Multiuser DOS and DR DOS 5.0 and higher) CONFIG$ (only in MS-DOS 7.0-8.0)

      Systems that have these restrictions cause incompatibilities with some other filesystems. For example, Windows will fail to handle, or raise error reports for, these legal UNIX filenames: aux.c, [22] q»uote»s.txt, or NUL.txt.

      NTFS filenames that are used internally include:

      $Mft, $MftMirr, $LogFile, $Volume, $AttrDef, $Bitmap, $Boot, $BadClus, $Secure, $Upcase, $Extend, $Quota, $ObjId and $Reparse

      Comparison of filename limitations [ edit ]

      System Case
      sensitive
      Case
      preserving
      Allowed character set Reserved characters Reserved words Maximum length (characters) Comments
      8-bit FAT ? ? 7-bit ASCII (but stored as bytes) first character not allowed to be 0x00 or 0xFF 9 Maximum 9 character base name limit for sequential files (without extension), or maximum 6 and 3 character extension for binary files; see 6.3 filename
      FAT12, FAT16, FAT32 No No any SBCS/DBCS OEM codepage 0x00-0x1F 0x7F » * / : < >? | + , . ; = [ ] (in some environments also: ! @ ; DOS 1/2 did not allow 0xE5 as first character) Device names including: $IDLE$ AUX COM1…COM4 CON CONFIG$ CLOCK$ KEYBD$ LPT1…LPT4 LST NUL PRN SCREEN$ (depending on AVAILDEV status everywhere or only in virtual DEV directory) 11 Maximum 8 character base name limit and 3 character extension; see 8.3 filename
      VFAT No Yes Unicode, using UCS-2 encoding 0x00-0x1F 0x7F » * / : < >? | 255
      exFAT No Yes Unicode, using UTF-16 encoding 0x00-0x1F 0x7F » * / : < >? | 255
      NTFS Optional Yes Unicode, using UTF-16 encoding 0x00-0x1F 0x7F » * / : < >? | Only in root directory: $AttrDef $BadClus $Bitmap $Boot $LogFile $MFT $MFTMirr pagefile.sys $Secure $UpCase $Volume $Extend $Extend$ObjId $Extend$Quota $Extend$Reparse ($Extend is a directory) 255 Paths can be up to 32,000 characters.

      Forbids the use of characters in range 1-31 (0x01-0x1F) and characters » * / : < >? | unless the name is flagged as being in the Posix namespace. NTFS allows each path component (directory or filename) to be 255 characters long [ dubious – discuss ] .

      Windows forbids the use of the MS-DOS device names AUX, CLOCK$, COM0, …, COM9, CON, LPT0, …, LPT9, NUL and PRN, as well as these names with any extension (for example, AUX.txt), except when using Long UNC paths (ex. \.C:nul.txt or \?D:auxcon). (CLOCK$ may be used, if an extension is provided.) The Win32 API strips trailing period (full-stop), and leading and trailing space characters from filenames, except when UNC paths are used. These restrictions only apply to Windows; in Linux distributions that support NTFS, filenames are written using NTFS’s Posix namespace, which allows any Unicode character except / and NUL.

      «Qualified» contains . after every 8 characters or fewer. [23] Partitioned data sets (PDS or PDSE) are divided into members with names of up to 8 characters; the member name is placed in parenthesises after the name of the PDS, e.g. PAYROLL.DEV.CBL(PROG001)

      See also [ edit ]

      • File system
      • Fully qualified file name
      • Long filename
      • Path (computing)
      • Slug (Web publishing)
      • Symbolic link
      • Uniform Resource Identifier (URI)
      • Uniform Resource Locator (URL) and Internationalized resource identifier
      • Windows (Win32) File Naming Conventions (Filesystem Agnostic)

      References [ edit ]

      1. ^ «CPM — CP/M disk and file system format».
      2. ^ abcdef David Robinson; Ienup Sung; Nicolas Williams (March 2006). «Solaris presentations: File Systems, Unicode, and Normalization» (PDF) . San Francisco: Sun.com. Archived from the original (PDF) on July 4, 2012.
      3. ^ RFC 959 IETF.org RFC 959, File Transfer Protocol (FTP)
      4. ^ «Fsutil command description page». Microsoft.com . Retrieved September 15, 2013 .
      5. ^ «NTFS Hard Links, Directory Junctions, and Windows Shortcuts». Flex hex. Inv Softworks . Retrieved March 12, 2011 .
      6. ^ ab «ddname support with FTP, z/OS V1R11.0 Communications Server IP User’s Guide and Commands z/OS V1R10.0-V1R11.0 SC31-8780-09». IBM.com.
      7. ^ «Maximum Path Length Limitation — Win32 apps».
      8. ^ «Filenames with accents». Ned Batchelder. June 2011 . Retrieved September 17, 2013 .
      9. ^ «NonNormalizingUnicodeCompositionAwareness — Subversion Wiki». Wiki.apache.org. January 21, 2013 . Retrieved September 17, 2013 .
      10. ^ «File Name Encoding Repair Utility v1.0». Support.apple.com. June 1, 2006 . Retrieved October 2, 2018 .
      11. ^ «convmv — converts filenames from one encoding to another». J3e.de . Retrieved September 17, 2013 .
      12. ^ «Re: git on MacOSX and files with decomposed utf-8 file names». KernelTrap. May 7, 2010. Archived from the original on March 15, 2011 . Retrieved July 5, 2010 .
      13. ^ «Cross platform filepath naming conventions — General Programming». GameDev.net . Retrieved September 17, 2013 .
      14. ^ «CaseInsensitiveFilenames — The Official Wine Wiki». Wiki.winehq.org. November 8, 2009. Archived from the original on August 18, 2010 . Retrieved August 20, 2010 .
      15. ^ «The Open Group Base Specifications Issue 6». IEEE Std 1003.1-2001. The Open Group. 2001.
      16. ^ «Naming Files, Paths, and Namespaces (Windows)». Msdn.microsoft.com. August 26, 2013 . Retrieved September 17, 2013 .
      17. ^ «Windows Naming Conventions». MSDN, Microsoft.com. See last bulleted item.
      18. ^ ab Naming a file msdn.microsoft.com (MSDN), filename restrictions on Windows
      19. ^Microsoft Windows 95 README for Tips and Tricks, Microsoft , retrieved August 27, 2015
      20. ^MS-DOS Device Driver Names Cannot be Used as File Names., Microsoft
      21. ^ abNaming Files, Paths, and Namespaces, Microsoft
      22. ^ Ritter, Gunnar (January 30, 2007). «The tale of «aux.c» «. Heirloom Project.
      23. ^ «Subparameter Definition, z/OS V1R11.0 MVS JCL Reference». IBM.com . Retrieved September 17, 2013 .
      24. ^ Lewine, Donald. POSIX Programmer’s Guide: Writing Portable UNIX Programs 1991 O’Reilly & Associates, Inc. Sebastopol, CA pp63-64
      25. ^ pathchk — check pathnames
      26. ^ Hewlett-Packard Company Roseville, CA HP 250 Syntax Reference Rev 1/84 Manual Part no 45260-90063

      External links [ edit ]

      • Data Formats Filename at Curlie
      • File Extension Library
      • FILExt
      • WikiExt — File Extensions Encyclopedia
      • Naming Files, Paths, and Namespaces (MSDN)
      • 2009 POSIX portable filename character set
      • Standard ECMA-208, December 1994, System-Independent Data Format
      • Best Practices for File Naming, USA: Stanford University Libraries, Data Management Services

      Смотрите также Как в Windows 10 включить поддержку пути к файлам длиной более 260 символов.

      Во всех операционных системах и для всех файловых систем существуют определённые лимиты на:

      • размер имени файла
      • на полный путь файла (который включает папки и подпапки)

      Операционная система Windows не является исключением, в ней длина имени файла или папки ограничена 255 символами, а вся длина пути ограничена примерно 32,000 символами.

      Имеется ряд исключений, когда разрешённая длина файла должна быть меньше этих значений:

      • предыдущие версии Windows
      • сетевые диски
      • оптические диски CD и DVD

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

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

      При поиске по файлам средствами ОС, эти файлы также недоступны для индексации и поиска по ним.

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

      Подтвердить проблему слишком длинного имени на сетевом носителе можно командой вида:

      dir "\путьдопапки"
      dir "\VBOXSVRShareАрхив работУП"

      вызывает следующую ошибку из-за того, что в папке имеется файл со слишком длинным именем:

      Каталог: \VBOXSVRShareАрхив работУП Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 24.08.2010 17:29 Общая часть d----- 17.02.2019 16:10 Особенная часть d----- 01.11.2018 10:24 Чужое dir : Параметр задан неверно. строка:1 знак:1 + dir "\VBOXSVRShareАрхив работУП" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ReadError: (\VBOXSVRShareАрхив работУП:String) [Get-ChildItem], IOException + FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand

      Если вы работаете с сетевым диском и он подключён к Linux, то вам может помочь инструкция «Как найти имена файлов, чья длина превышает определённое значение».

      В остальных случаях, попробуйте следующие советы:

      1. (если слишком длинный путь до файла) Вначале скопируйте папку на более высокие уровни в windows эксплорере и затем переместите их на ваш локальный компьютер

      2. (если имена файлов слишком длинные) Вначале попробуйте поместить их в архив программами zip/rar/7z и затем скопируйте файл архива на свой локальный компьютер и извлеките его содержимое

      3. Попробуйте встроенную программу ROBOCOPY:

      robocopy /E ИСТОЧНИК НАЗНАЧЕНИЕ

      4. Попробуйте перед путём добавить \?

      \?C:SomeReallyLongPath

      5. Используйте сторонне программное обеспечение (о нём далее)

      FastCopy — это проект с открытым исходным кодом на C, написанный SHIROUZU Hiroaki и это «Самое быстрое программное обеспечение для копирования/удаления файлов на Windows.» Программа поддеррживает UNICODE и более чем MAX_PATH (260 символов) в путях имён файлов.

      Если имеются сотни путей, которые слишком долго исправлять, то используйте инструмент «Path Tool Long Auto Fixer».

      Связанные статьи:

      • Как в Windows 10 включить поддержку пути к файлам длиной более 260 символов (93.2%)
      • Как переименовать файл или папку в PowerShell (64.4%)
      • Создание жёстких и мягких ссылок с помощью PowerShell (64.4%)
      • Как создать общую сетевую папку на Windows (56.8%)
      • Как подключиться к сетевой папке в Windows (SMB) (56.8%)
      • Как ограничить скорость загрузки обновлений Windows 10 (RANDOM — 50%)

      Большинство администраторов и пользователей 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. Перейдите в раздел редактора LocalComputerPolicy ->ComputerConfiguration ->AdministrativeTemplates ->System ->Filesystem ->NTFS (Конфигурация компьютера -> Административные шаблоны -> Система -> Файловая система -> NTFS)Групповые политики NTFS
      3. Откройте политику Enable NTFS long pathsEnable NTFS long paths включить поддержку путей более 260 символов
      4. Включите политику, переведя ее в состояние Enabled
      5. Сохраните изменения

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

      LongPathsEnabled - параметр реестра

      1. Запустите редактор реестра regedit.exe
      2. Перейдите в ветку HKEY_CURRENT_USERSOFTWAREMicrosoftWindowsCurrentVersionGroup Policy ObjectsMachineSystemCurrentControlSetPolicies
      3. Создайте в данной ветке новый параметр типа Dword(32-bit)Value с именем LongPathsEnabled
      4. Чтобы отключить ограничение MAX_PATH, измените значение ключа на 1

      Также вы можете включить эту функцию одной командой PowerShell:
      Set-ItemProperty -Path HKLM:SYSTEMCurrentControlSetControlFileSystem -Name LongPathsEnabled -Value 1

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

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

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

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

      Существует большая история длины файлов, что является проблемой для операционных систем, таких как Windows. Было время, когда вы не могли иметь имена файлов длиннее 8 символов плюс 3-символьное расширение файла. Лучшее, что вы могли сделать, это что-то вроде myresume.doc. Это было ограничение в отношении дизайна файловой системы.

      Все стало лучше, когда вышли новые версии Windows. Мы перешли от старой ограниченной файловой системы к так называемой файловой системе новой технологии (NTFS). NTFS привела нас к тому, что имя файла может быть длиной 255 символов, а длина пути к файлу потенциально может достигать 32 767 символов. Так как же мы можем иметь слишком длинные имена файлов?

      В Windows есть вещи, известные как системные переменные. Это переменные, от которых зависит функционирование Windows, потому что Windows всегда будет знать, что означают переменные и где они находятся, даже когда мы перемещаем биты и байты повсюду. Системная переменная MAX_PATH — это та, которая ограничивает имена файлов и пути к файлам до 260 символов.

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

      Настройка Windows 10 на обработку длинных путей к файлам

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

      Есть два способа сделать это. Один предназначен для пользователей Windows 10 Home, а другой — для пользователей Windows 10 Pro или Enterprise. Эти методы могут работать для Windows 8.1 или более ранней версии, но мы не можем гарантировать это.

      Параметры для Windows 10 Home

      Чтобы Windows 10 Home принимала длинные пути к файлам, нам нужно открыть редактор реестра . Если вы раньше не работали в редакторе реестра, будьте осторожны. Случайное удаление или изменение здесь может помешать работе Windows полностью.

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

      Открыв редактор реестра и сделав резервную копию, перейдите в папку HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlFileSystem и найдите ключ LongPathsEnabled.

      Дважды щелкните LongPathsEnabled. Убедитесь, что в поле Значение данные: номер 1 указан. Нажмите OK, чтобы подтвердить изменения.

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

      Параметры для Windows 10 Pro или Enterprise

      Чтобы позволить Windows 10 Pro или Enterprise использовать длинные пути к файлам, мы будем использовать редактор локальной групповой политики. Это инструмент, который позволяет нам устанавливать политики в отношении работы Windows на компьютере и на уровне пользователей.

      Откройте редактор групповой политики, перейдя в меню «Пуск» и набрав gpedit . Лучший результат должен быть Изменить групповую политику. Дважды щелкните по этому.

      После открытия редактора групповой политики перейдите к Конфигурация компьютера → Административные шаблоны → Система → Файловая система. Там вы увидите политику включения длинных путей Win32.

      Дважды щелкните по нему, чтобы изменить параметр политики. Измените его с «Отключено» на «Включено», затем нажмите кнопку «ОК», чтобы зафиксировать изменение.

      Политика может не вступить в силу сразу. Вы можете принудительно обновить групповую политику.

      Как временно исправить проблему с файлами?

      Легкое Исправление

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

      C:UserguymcDocumentsMy Resumesresumewithanamesolongthatitcausesproblemsandbecomespartofsomeguysarticleonthewebhowdoyoulikemenow.docx

      Понятно, кто в этом случае виновник. Найдите файл в проводнике Windows или в проводнике, как он называется в Windows 10, нажмите один раз на него, нажмите F2, чтобы переименовать его, и измените это глупое имя файла на более разумное. Задача решена.

      Менее простые исправления

      Не всегда легко решить эту проблему. Иногда вы не можете изменить имена файлов или каталогов по любой причине.

      Следующие решения помогут вам. Их несложно сделать.

      Перемещение, удаление или копирование файлов или каталогов с помощью PowerShell
      Иногда вы получаете сообщение об ошибке при попытке переместить, удалить или скопировать каталоги, где количество символов для пути к файлу превышает 260.

      Обратите внимание, что слова каталог и папка являются взаимозаменяемыми. Мы будем использовать «каталог» в будущем. Следующие командлеты PowerShell также можно использовать для файлов.

      Возможно, путь к файлу выглядит примерно так:

      C:UsersguymcDocumentsThisIsExactlyThePreciseDirectoryPathThatINeedToHaveToKeepMyFilesSortedInAMannerThatMakesSenseToMeSoLetsPretendThisIsAnActualFilepathThatYouMightAlsoHaveOnYourWindowsComputerAndNotOverThinkItDocument.docx

      Этот путь к файлу составляет 280 символов. Поэтому мы не можем скопировать каталог оттуда куда-либо еще с помощью обычного метода копирования-вставки. Мы получаем ошибку Destination Path Too Long.

      Давайте предположим, что по какой-то причине мы не можем переименовать каталоги, в которые вложен файл. Что мы делаем?

      Когда откроется PowerShell, вы окажетесь в корне своего пользовательского каталога. Продолжайте, предполагая, что C:Usersguymc — ваш пользовательский каталог.

      Каталог с именем This находится в каталоге Documents. Чтобы перейти в каталог Documents, мы используем команду cd Documents .

      Вы увидите быстрое изменение текущего каталога на C:UsersguymcDocuments. Это хорошо. Мы работаем ближе к каталогам, которые облегчат жизнь.

      Копирование каталога с использованием Copy-Item

      Мы хотим скопировать каталог This и его содержимое в ThatNewFolder. Давайте используем команду PowerShell Copy-Item с параметрами -Destination и -Recurse.

      -Destination сообщает PowerShell, где мы хотим, чтобы копия находилась. -Recurse говорит PowerShell скопировать все элементы внутри к месту назначения. Копирование оставляет оригиналы там, где они есть, и делает все новые в месте назначения.

      Copy-Item This -Destination ThatNewFolder -Recurse

      Переместить каталог с помощью Move-Item

      Допустим, мы хотим переместить каталог This, а также все каталоги и файлы в нем, в ThatNewFolder. Перемещение не оставляет оригинал на месте.

      Мы можем использовать команду PowerShell Move-Item с параметрами -Path и -Destination. -Path определяет элемент, который мы хотим переместить, и -Destination сообщает PowerShell, где мы хотим его получить.

      Команда поместит это в ThatNewFolder. Он также будет перемещать все, что находится внутри этого каталога. Move-Item может использоваться для перемещения файлов или каталогов, и он работает независимо от пути к файлу или длины имени файла.

      Move-Item -Path This -Destination ThatNewFolder

      Чтобы убедиться, что это работает, используйте команду cd ThatNewFolder , чтобы войти в ThatNewFolder. Затем используйте команду dir для вывода списка каталогов в ThatNewFolder. Вы увидите, что этот каталог находится там.

      Удалить каталог с помощью Remove-Item

      Если мы хотим удалить этот каталог и все в нем, мы используем команду Remove-Item.

      Командлет Remove-Item обладает некоторой встроенной безопасностью, которая затрудняет удаление каталога с содержимым внутри него. В нашем примере мы знаем, что хотим удалить все, поэтому мы будем использовать параметры -Recurse, чтобы заставить его удалять все внутри, и -Force, чтобы он делал это, не спрашивая нас, уверены ли мы в каждом элементе внутри.

      Имейте в виду! Восстановить что-либо удаленное таким образом было бы чрезвычайно сложно.

      Remove-Item This -Recurse -Force

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

      Вот и все

      Существуют и другие способы обхода длинных имен файлов и путей к файлам, но то, что мы здесь рассмотрели, — это самые простые и эффективные методы.