- Directory. Delete Метод
- Определение
- Перегрузки
- Delete(String)
- Параметры
- Исключения
- Примеры
- Комментарии
- Применяется к
- Delete(String, Boolean)
- Параметры
- Исключения
- Примеры
- Комментарии
- cmd Delete Folder – How to Remove Files and Folders in Windows
- Kris Koishigawa
- How to open Command Prompt
- How to delete files with the del command
- How to force delete files with the del command
- How to delete folders with the rmdir command
- How to use the /s flag with rmdir
- Kris Koishigawa
Directory. Delete Метод
Определение
Удаляет заданный каталог и при необходимости все подкаталоги. Deletes a specified directory, and optionally any subdirectories.
Перегрузки
Удаляет пустой каталог по заданному пути. Deletes an empty directory from a specified path.
Удаляет заданный каталог и, при наличии соответствующей инструкции, все подкаталоги и файлы в нем. Deletes the specified directory and, if indicated, any subdirectories and files in the directory.
Delete(String)
Удаляет пустой каталог по заданному пути. Deletes an empty directory from a specified path.
Параметры
Имя пустого каталога, который необходимо удалить. The name of the empty directory to remove. Этот каталог должен поддерживать запись и быть пустым. This directory must be writable and empty.
Исключения
Файл с тем же именем и расположении, заданном path , уже существует. A file with the same name and location specified by path exists.
-или- -or- Каталог является текущим рабочим каталогом приложения. The directory is the application’s current working directory.
-или- -or- Каталог, заданный параметром path , не пустой. The directory specified by path is not empty.
-или- -or- Каталог доступен только для чтения или содержит файл, доступный только для чтения. The directory is read-only or contains a read-only file.
-или- -or- Каталог используется другим процессом. The directory is being used by another process.
У вызывающего объекта отсутствует необходимое разрешение. The caller does not have the required permission.
path представляет собой строку нулевой длины, содержащую только пробелы или один или несколько недопустимых символов. path is a zero-length string, contains only white space, or contains one or more invalid characters. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars(). You can query for invalid characters by using the GetInvalidPathChars() method.
path имеет значение null . path is null .
Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе. The specified path, file name, or both exceed the system-defined maximum length.
Параметр path не существует или не найден. path does not exist or could not be found.
-или- -or- Указан недопустимый путь (например, он ведет на несопоставленный диск). The specified path is invalid (for example, it is on an unmapped drive).
Примеры
В следующем примере показано, как создать новый каталог и подкаталог, а затем удалить только подкаталог. The following example shows how to create a new directory and subdirectory, and then delete only the subdirectory.
Комментарии
Этот метод ведет себя так же, как и аргумент, Delete(String, Boolean) false указанный для второго параметра. This method behaves identically to Delete(String, Boolean) with false specified for the second parameter.
path Параметр может указывать сведения относительного или абсолютного пути. The path parameter may specify relative or absolute path information. Сведения об относительном пути интерпретируется как относительно текущего рабочего каталога. Relative path information is interpreted as relative to the current working directory. Сведения о получении текущего рабочего каталога см. в разделе GetCurrentDirectory . To obtain the current working directory, see GetCurrentDirectory.
Конечные пробелы удаляются из конца path параметра перед удалением каталога. Trailing spaces are removed from the end of the path parameter before deleting the directory.
Этот метод создает исключение, IOException Если каталог, указанный в path параметре, содержит файлы или подкаталоги. This method throws an IOException if the directory specified in the path parameter contains files or subdirectories.
path Параметр не учитывает регистр. The path parameter is not case-sensitive.
В некоторых случаях, если указанный каталог открыт в проводнике, Delete метод может не иметь возможности его удалить. In some cases, if you have the specified directory open in File Explorer, the Delete method may not be able to delete it.
Применяется к
Delete(String, Boolean)
Удаляет заданный каталог и, при наличии соответствующей инструкции, все подкаталоги и файлы в нем. Deletes the specified directory and, if indicated, any subdirectories and files in the directory.
Параметры
Имя каталога, который необходимо удалить. The name of the directory to remove.
Значение true позволяет удалить каталоги, подкаталоги и файлы по заданному path , в противном случае — значение false . true to remove directories, subdirectories, and files in path ; otherwise, false .
Исключения
Файл с тем же именем и расположении, заданном path , уже существует. A file with the same name and location specified by path exists.
-или- -or- Каталог, заданный параметром path , доступен только для чтения, или recursive имеет значение false и path не является пустым каталогом. The directory specified by path is read-only, or recursive is false and path is not an empty directory.
-или- -or- Каталог является текущим рабочим каталогом приложения. The directory is the application’s current working directory.
-или- -or- Каталог содержит файл только для чтения. The directory contains a read-only file.
-или- -or- Каталог используется другим процессом. The directory is being used by another process.
У вызывающего объекта отсутствует необходимое разрешение. The caller does not have the required permission.
path представляет собой строку нулевой длины, содержащую только пробелы или один или несколько недопустимых символов. path is a zero-length string, contains only white space, or contains one or more invalid characters. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars(). You can query for invalid characters by using the GetInvalidPathChars() method.
path имеет значение null . path is null .
Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе. The specified path, file name, or both exceed the system-defined maximum length.
Параметр path не существует или не найден. path does not exist or could not be found.
-или- -or- Указан недопустимый путь (например, он ведет на несопоставленный диск). The specified path is invalid (for example, it is on an unmapped drive).
Примеры
В следующем примере показано, как создать новый каталог, подкаталог и файл в подкаталоге, а затем рекурсивно удалить все новые элементы. The following example shows how to create a new directory, subdirectory, and file in the subdirectory, and then recursively delete all the new items.
Комментарии
path Параметр может указывать сведения относительного или абсолютного пути. The path parameter may specify relative or absolute path information. Сведения об относительном пути интерпретируется как относительно текущего рабочего каталога. Relative path information is interpreted as relative to the current working directory. Сведения о получении текущего рабочего каталога см. в разделе GetCurrentDirectory . To obtain the current working directory, see GetCurrentDirectory.
Конечные пробелы удаляются из конца path параметра перед удалением каталога. Trailing spaces are removed from the end of the path parameter before deleting the directory.
path Параметр не учитывает регистр. The path parameter is not case-sensitive.
Если recursive параметр имеет значение true , пользователь должен иметь разрешение на запись для текущего каталога, а также для всех подкаталогов. If the recursive parameter is true , the user must have write permission for the current directory as well as for all subdirectories.
Поведение этого метода немного отличается при удалении каталога, содержащего точку повторного анализа, например символическую ссылку или точку подключения. The behavior of this method differs slightly when deleting a directory that contains a reparse point, such as a symbolic link or a mount point. Если точка повторного анализа является каталогом, например точкой подключения, она отключается и точка подключения удаляется. If the reparse point is a directory, such as a mount point, it is unmounted and the mount point is deleted. Этот метод не выполняет рекурсивный перебор точки повторного анализа. This method does not recurse through the reparse point. Если точка повторного анализа является символьной ссылкой на файл, то точка повторного анализа удаляется, а не целевой объект символьной ссылки. If the reparse point is a symbolic link to a file, the reparse point is deleted and not the target of the symbolic link.
В некоторых случаях, если указанный каталог открыт в проводнике, Delete метод может не иметь возможности его удалить. In some cases, if you have the specified directory open in File Explorer, the Delete method may not be able to delete it.
cmd Delete Folder – How to Remove Files and Folders in Windows
Kris Koishigawa
Sometimes it’s just faster to do things with the command line.
In this quick tutorial we’ll go over how to open Command Prompt, some basic commands and flags, and how to delete files and folders in Command Prompt.
If you’re already familiar with basic DOS commands, feel free to skip ahead.
How to open Command Prompt
To open Command Prompt, press the Windows key, and type in «cmd».
Then, click on «Run as Administrator»:
After that, you’ll see a Command Prompt window with administrative privileges:
Screenshot of Command Prompt window
If you can’t open Command Prompt as an administrator, no worries. You can open a normal Command Prompt window by clicking «Open» instead of «Run as Administrator».
The only difference is that you may not be able to delete some protected files, which shouldn’t be a problem in most cases.
How to delete files with the del command
Now that Command Prompt is open, use cd to change directories to where your files are.
I’ve prepared a directory on the desktop called Test Folder. You can use the command tree /f to see a, well, tree, of all the nested files and folders:
To delete a file, use the following command: del » » .
For example, to delete Test file.txt , just run del «Test File.txt» .
There may be a prompt asking if you want to delete the file. If so, type «y» and hit enter.
Note: Any files deleted with the del command cannot be recovered. Be very careful where and how you use this command.
After that, you can run tree /f to confirm that your file was deleted:
Also, bonus tip – Command Prompt has basic autocompletion. So you could just type in del test , press the tab key, and Command Prompt will change it to del «Test File.txt» .
How to force delete files with the del command
Sometimes files are marked as read only, and you’ll see the following error when you try to use the del command:
To get around this, use the /f flag to force delete the file. For example, del /f «Read Only Test File.txt» :
How to delete folders with the rmdir command
To delete directories/folders, you’ll need to use the rmdir or rd command. Both commands work the same way, but let’s stick with rmdir since it’s a bit more expressive.
Also, I’ll use the terms directory and folder interchangeably for the rest of the tutorial. «Folder» is a newer term that became popular with early desktop GUIs, but folder and directory basically mean the same thing.
To remove a directory, just use the command rmdir .
Note: Any directories deleted with the rmdir command cannot be recovered. Be very careful where and how you use this command.
In this case I want to remove a directory named Subfolder, so I’ll use the command rmdir Subfolder :
But, if you remember earlier, Subfolder has a file in it named Nested Test File.
You could cd into the Subfolder directory and remove the file, then come back with cd .. and run the rmdir Subfolder command again, but that would get tedious. And just imagine if there were a bunch of other nested files and directories!
Like with the del command, there’s a helpful flag we can use to make things much faster and easier.
How to use the /s flag with rmdir
To remove a directory, including all nested files and subdirectories, just use the /s flag:
There will probably be a prompt asking if you want to remove that directory. If so, just type «y» and hit enter.
And that’s it! That should be everything you need to know to remove files and folders in the Windows Command Prompt.
All of these commands should work in PowerShell, which is basically Command Prompt version 2.0. Also, PowerShell has a bunch of cool aliases like ls and clear that should feel right at home if you’re familiar with the Mac/Linux command line.
Did these commands help you? Are there any other commands that you find useful? Either way, let me know over on Twitter.
Kris Koishigawa
Read more posts by this author.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.