- Directory. Delete Метод
- Определение
- Перегрузки
- Delete(String)
- Параметры
- Исключения
- Примеры
- Комментарии
- Применяется к
- Delete(String, Boolean)
- Параметры
- Исключения
- Примеры
- Комментарии
- How to delete a file, directory, or folder
- How to delete files in Microsoft Windows
- Delete key
- Delete file or folder by right-clicking
- Delete from file menu
- Problems during delete
- Windows command line
- Uninstalling a program
- How to restore a deleted file or folder
- How to delete files in MS-DOS and the Windows command line
- Files
- Delete multiple files
- Directory
- Deleting a subdirectory
- How to delete a directory or file name with a space
- How to delete files in Linux, Unix, and other variants
- Files
- Delete multiple files
- Directory
- Deleting a subdirectory
- How to delete a directory or file name with a space
- How to delete files on macOS
- Delete key
- Right-click and choosing Move to Trash
- Delete from the file menu
- Terminal
- How to delete files on Microsoft Windows 3.X
- File Manager
- MS-DOS
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.
How to delete a file, directory, or folder
The steps to delete a computer file, directory, or folder vary on the method you’d like to use, and your operating system. To proceed, choose from the list of options below and follow the instructions.
How to delete files in Microsoft Windows
Microsoft Windows users can delete a file or folder (directory) using many different methods. Below are the more common methods for deleting a file or folder in Microsoft Windows.
Users not familiar with Windows should realize that if you delete a folder, it deletes all the files and folders within that folder.
The steps below are for deleting a single file or folder. However, the same steps can be done to delete multiple files or folders. For help with selecting multiple files, see: How to select or highlight multiple files and folders.
Delete key
Locate the item you want to delete, highlight it by clicking the file or folder once, and press the Delete key. You can browse to the location of the file or folder using either My Computer or Windows Explorer.
You can delete multiple files or folders by holding down the Ctrl key and clicking each before pressing Delete .
You can hold down the Shift key while pressing the Delete key to prevent the files being deleted from going to the Recycle Bin.
Delete file or folder by right-clicking
Open My Computer or Windows Explorer. Locate the file or folder you want to delete and right-click it. Choose the delete option from the pop-up menu.
Delete from file menu
Open My Computer or Windows Explorer, locate and select the file or folder you want to delete, click File in the top menu bar and select Delete.
If the File menu is not visible in My Computer or Windows Explorer, press the Alt key to make the menu bar visible, including the file menu.
Problems during delete
Some files and folders may be protected from deletion through encryption or password protection. In this case, you may be asked for a password to decrypt or remove the password protection.
A file may be set as a read-only file, meaning it can only be opened for viewing, but it cannot be modified or deleted. When trying to delete a read-only file, you’ll get a message stating the file is write-protected and cannot be deleted. You’ll need modify or write permissions to be granted to your user account to delete the file.
Some files may only be deleted with administrator permissions. To delete these files, you would need to have administrator rights on the computer. If you are using a work computer, the technical support staff often are the only users with administrator rights on the computer.
Another possible cause of problems with deleting a file or folder is a virus or malware infection. Viruses and malware can prevent files or folders from being modified or deleted. If this is the case, you need to remove the virus or malware infection to be able to delete the affected file or folder.
Windows command line
See the below MS-DOS and Windows command line section for information about deleting a file or folder at the Windows command line.
Uninstalling a program
See our uninstalling a program steps for help with uninstalling (deleting) software programs from the computer.
How to restore a deleted file or folder
If you’ve deleted a file by mistake, you can see our steps on how to restore a deleted file page for further information on recovering a deleted file.
How to delete files in MS-DOS and the Windows command line
Keep in mind that any deleted file or directory in MS-DOS is not be sent to the Windows Recycle Bin.
Before any of the steps below can be followed, you must get to an MS-DOS prompt or the Windows command line. If you are new to the command line, you may also want to read through the following pages first.
- How to get to an MS-DOS prompt or Windows command line.
- How to use the Windows command line (DOS).
Files
MS-DOS users can delete files using the del command. See this page to get additional information and help with this command. Below is an example of how this command could be used.
As seen in the above example, when deleting a file, you need to enter the full file name including the file extension.
The del command can delete any file.
Delete multiple files
You can also use wildcards if you want to delete multiple files as shown in the example below.
In the above example, this command would delete all files that end with a .txt file extension.
The del command can delete any file extension.
Directory
MS-DOS users can delete directories in MS-DOS using the deltree command or rmdir command. See either of these links for additional information about these commands. Below is an example of how this could be used.
If the directory is full or has other subdirectories, you’ll get an error message. To delete a full directory, you need to use a switch with the above example. For example, «rmdir example /s» to remove a full «example» directory. See our deltree command or rmdir command for additional examples and switches.
Deleting a subdirectory
If you want to delete a directory within another directory (subdirectory), you can use a command similar to the example below.
In the above example, the «test» directory in the «example» directory would be deleted. You could also use the cd command to change the directory to the example directory and then delete the «test» directory using our first example shown above.
How to delete a directory or file name with a space
To delete a directory or file name with a space in the name, you must surround the directory or file name with quotes as shown below.
In the above examples, we are deleting the file named «my example file.txt» with quotes surrounding the complete file name and extension and removing the «my example directory» directory.
The rmdir command can delete any file.
How to delete files in Linux, Unix, and other variants
Files
Linux and Unix users can delete files through the console using the rm command. See this page for additional information about this command. Below is an example of how this command could be used.
As seen in the example above, when deleting a file, you need to enter the full file name including the file extension.
The rm command can delete any file.
Delete multiple files
You can also use wildcards if you want to delete multiple files, as shown in the example below.
In the example above, this command would delete all files with a .txt file extension.
The rm command can delete any file of file extensions.
Directory
Linux and Unix users can delete folders through the console with the rmdir command. See this page for additional information about this command. Below is an example of how this command could be used.
Like Microsoft Windows, with Linux and Unix, you can also delete files through the GUI by locating the file and pressing the delete key on the keyboard.
Deleting a subdirectory
If you want to delete a directory within another directory (subdirectory), you can use a command similar to the example below.
In the example above, the «test» directory in the «example» directory would be deleted. You could also use the cd command to change the directory to the example directory and then delete the «test» directory using our first example shown above.
How to delete a directory or file name with a space
To delete a directory or file name with a space in the name, you must surround the directory or file name with quotes as shown below.
In the examples above, we are deleting the file named «my example file.txt» with quotes surrounding the complete file name and extension and removing the «my example directory» directory.
The rmdir command can delete any file.
How to delete files on macOS
Apple macOS users can delete a file or folder (directory) using many different methods. Below are the more common methods for deleting a file or folder.
Users not familiar with Apple macOS should realize that if you delete a folder, it deletes all the files and folders in that folder.
The steps below are for deleting a single file or folder. However, the same steps can be applied to deleting multiple files or folders if you select several files or folders first. See: How to select or highlight multiple files and folders.
Delete key
The delete on the keyboard by itself does not delete a file or folder on macOS. To delete a file or folder, press and hold Command , then press the delete key. You can browse to the location of the file or folder using Finder.
Right-click and choosing Move to Trash
Open Finder, locate the file or folder you want to delete, and right-click the file or folder. In the right-click menu that appears, click the Move to Trash option.
Delete from the file menu
Open Finder, locate and select the file or folder you want to delete, click File in the top menu bar, and select Move to Trash.
Terminal
To delete files or directories in the Terminal command line, use the rm command.
How to delete files on Microsoft Windows 3.X
File Manager
- Open File Manager
- Locate the folder or file you want to delete, then click File and Delete.
MS-DOS
See the MS-DOS user section above for information about deleting a directory in MS-DOS.