File.Delete(String) Метод
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Удаляет указанный файл.
public:
static void Delete(System::String ^ path);
public static void Delete (string path);
static member Delete : string -> unit
Public Shared Sub Delete (path As String)
- path
- String
Имя файла, предназначенного для удаления. Подстановочные знаки не поддерживаются.
платформа .NET Framework и .NET Core версий старше 2.1: path
строка нулевой длины, содержит только пробелы или содержит один или несколько недопустимых символов. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars().
path
имеет значение null
.
Указан недопустимый путь (например, он ведет на несопоставленный диск).
Указанный файл используется.
-или-
Для файла имеется открытый дескриптор, а операционной системой является Windows XP или более ранней версии. Этот открытый дескриптор может быть результатом перечисления каталогов и файлов. Дополнительные сведения см. в разделе Практическое руководство. Перечисление каталогов и файлов.
Параметр path
задан в недопустимом формате.
Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе.
У вызывающего объекта отсутствует необходимое разрешение.
-или-
Файл является исполняемым файлом, который уже используется.
-или-
path
является каталогом.
-или-
Параметр path
указывает файл только для чтения.
В следующем примере группы файлов копируются в папку резервного копирования C:\archives\2008, а затем удаляются из исходной папки.
string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy picture files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Delete source files that were copied.
foreach (string f in txtList)
{
File.Delete(f);
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
let sourceDir = @"c:\current"
let backupDir = @"c:\archives\2008"
try
let picList = Directory.GetFiles(sourceDir, "*.jpg")
let txtList = Directory.GetFiles(sourceDir, "*.txt")
// Copy picture files.
for f in picList do
// Remove path from the file name.
let fName = f.Substring(sourceDir.Length + 1)
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true)
// Copy text files.
for f in txtList do
// Remove path from the file name.
let fName = f.Substring(sourceDir.Length + 1)
try
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))
// Catch exception if the file was already copied.
with
| :? IOException as copyError -> printfn $"{copyError.Message}"
// Delete source files that were copied.
for f in txtList do
File.Delete f
for f in picList do
File.Delete f
// Catch exception if the file was already copied.
with
| :? DirectoryNotFoundException as dirNotFound -> printfn $"{dirNotFound.Message}"
Dim sourceDir As String = "c:\current"
Dim backupDir As String = "c:\archives\2008"
Try
Dim picList As String() = Directory.GetFiles(sourceDir, "*.jpg")
Dim txtList As String() = Directory.GetFiles(sourceDir, "*.txt")
' Copy picture files.
For Each f As String In picList
'Remove path from the file name.
Dim fName As String = f.Substring(sourceDir.Length + 1)
' Use the Path.Combine method to safely append the file name to the path.
' Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), True)
Next
' Copy text files.
For Each f As String In txtList
'Remove path from the file name.
Dim fName As String = f.Substring(sourceDir.Length + 1)
Try
' Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))
' Catch exception if the file was already copied.
Catch copyError As IOException
Console.WriteLine(copyError.Message)
End Try
Next
For Each f As String In txtList
File.Delete(f)
Next
For Each f As String In picList
File.Delete(f)
Next
Catch dirNotFound As DirectoryNotFoundException
Console.WriteLine(dirNotFound.Message)
End Try
Укажите имя файла с любыми относительными или абсолютными сведениями о пути для path
параметра . Подстановочные знаки не могут быть включены. Сведения об относительном пути интерпретируются как относительные относительно текущего рабочего каталога. Сведения о том, как получить текущий рабочий каталог, см. в разделе GetCurrentDirectory.
Если удаляемого файла не существует, исключение не создается.
Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.
Продукт | Версии |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.3, 1.4, 1.6, 2.0, 2.1 |
UWP | 10.0 |
Отзыв о .NET
.NET — это проект с открытым исходным кодом. Выберите ссылку, чтобы оставить отзыв: