File.Delete(String) Método
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Exclui o arquivo especificado.
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)
Parâmetros
- path
- String
O nome do arquivo a ser excluído. Não há suporte para caracteres curinga.
Exceções
.NET Framework e versões do .net Core anteriores a 2,1: path
é uma cadeia de caracteres de comprimento zero, contém apenas espaço em branco ou contém um ou mais caracteres inválidos. Consulte caracteres inválidos usando o método GetInvalidPathChars().
path
é null
.
O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).
O arquivo especificado está sendo usado.
- ou - Há um identificador aberto no arquivo, e o sistema operacional é o Windows XP ou uma versão anterior. Esse identificador aberto pode resultar da enumeração de diretórios e arquivos. Para obter mais informações, consulte How to: Enumerate Directories and Files (Como enumerar diretórios e arquivos).
path
está em um formato inválido.
O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.
O chamador não tem a permissão necessária.
- ou - O arquivo é um arquivo executável que está sendo usado.
- ou -
path
é um diretório.
- ou -
path
especificou um arquivo somente leitura.
Exemplos
O exemplo a seguir copia grupos de arquivos para a pasta de backup C:\archives\2008 e os exclui da pasta de origem.
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);
}
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
Comentários
Especifique um nome de arquivo com qualquer informação de caminho relativa ou absoluta para o path
parâmetro. Não é possível incluir caracteres curinga. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory .
Se o arquivo a ser excluído não existir, nenhuma exceção será lançada.
Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.