Форум программистов, компьютерный форум, киберфорум
Dragokas
Войти
Регистрация
Восстановить пароль
Карта форума Блоги Сообщество Поиск Заказать работу  
Оценить эту запись

Удаление файлов/папок с зарезервированными именами

Запись от Dragokas размещена 15.09.2012 в 23:43
Обновил(-а) Dragokas 26.08.2013 в 00:05

Bash
1
2
\\?\
\\.\
Отключает на время выполнения команды API-функции, накладывающие следующие запреты:

- операции с файлами/папками с зарезервированными именами.
- обращение к разделу напрямую через точку монтирования.


А также:
Bash
1
\\?\
- для обхода ограничения на максимальную общую длину каталога в 256 символов.
- отключает парсинг большинства спецсимволов.


Цитата:
For file I/O, the "\\?\" prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system. For example, if the file system supports large paths and file names, you can exceed the MAX_PATH limits that are otherwise enforced by the Windows APIs.

Because it turns off automatic expansion of the path string, the "\\?\" prefix also allows the use of ".." and "." in the path names, which can be useful if you are attempting to perform operations on a file with these otherwise reserved relative path specifiers as part of the fully qualified path.
Bash
1
\\.\
- для обращения к устройствам напрямую в обход файловой системы.

Цитата:
The "\\.\" prefix will access the Win32 device namespace instead of the Win32 file namespace. This is how access to physical disks and volumes is accomplished directly, without going through the file system, if the API supports this type of access. You can access many devices other than disks this way (using the CreateFile and DefineDosDevice functions, for example).

Another example of using the Win32 device namespace is using the CreateFile function with "\\.\PhysicalDiskX" (where X is a valid integer value) or "\\.\CdRomX". This allows you to access those devices directly, bypassing the file system. This works because these device names are created by the system as these devices are enumerated, and some drivers will also create other aliases in the system. For example, the device driver that implements the name "C:\" has its own namespace that also happens to be the file system.
Примеры практического использования:

1) Обращение к разделу напрямую через точку монтирования:
Bash
1
2
type \\?\Volume{98fc8064-566a-11d9-82a2-806d6172696f}\out.txt
type \\.\Volume{98fc8064-566a-11d9-82a2-806d6172696f}\out.txt
К примеру, если разделу не назначено имя диска.
Список таких точек можно получить штатной утилитой MOUNTVOL.exe без параметров.
Примеры также можете почитать в статьях Криса Касперского - один, два.
И в этой теме: Программно скрыть каталог или жёсткий диск

2) Создание виртуального жесткого диска VHD и подключение его как пустой папки через точку монтирования.

Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@echo off
SetLocal EnableExtensions
call :Invoke_UAC %*
 
set vdisk=c:\vdisk.vhd
 
mountvol /E
For /F "delims=" %%? in ('mountvol ^| find "\\?\"') do set Array.%%?=true
(
  echo create vdisk file="%vdisk%" maximum=512 type=fixed
  echo select vdisk file="%vdisk%"
  echo attach vdisk
  echo convert mbr
  echo create partition primary
  echo format fs=NTFS label="VDisk" quick
) | diskpart
For /F "delims=" %%? in ('mountvol ^| find "\\?\"') do if not defined Array.%%? set MountPoint=%%?
mklink /d c:\VDisk\ %MountPoint%
pause
Exit
 
:Invoke_UAC :: Затребование диалога UAC повышения прав
  ver |>nul find "6." && if "%1"=="" (
    Echo new ActiveXObject^('Shell.Application'^).ShellExecute ^(WScript.Arguments^(0^),'UAC','','runas',1^);>"%~dp0Invoke_UAC.js"
    cscript.exe //nologo //e:jscript "%~dp0Invoke_UAC.js" "%~f0"& Exit
  ) else (>nul del "%~dp0Invoke_UAC.js"& chdir /d "%~dp0")
Exit /B
Обсуждается в теме: Подключение виртуального жесткого диска VHD как пустой папки с помощью симлинка

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

Bash
1
2
3
4
5
6
7
8
@echo off
chcp 1251
for /f "delims=" %%i in ('dir /b /a:d') do (
  chcp 866
  rmdir /s "\\.\%%i\"
  chcp 1251
)
pause>nul
Другие ссылки по теме:

Path (computing) - Wikipedia
MSDN - Naming Files, Paths, and Namespaces
MSDN - Naming a Volume

wiki.drweb.com/index.php/Каталог_E2E2~1
MSKB - Невозможно удалить файл или папку в томе с файловой системой NTFS
MSKB - Удаление файлов с зарезервированными именами в Windows XP
Размещено в Без категории
Показов 4839 Комментарии 0
Всего комментариев 0
Комментарии
 
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru