File.Delete(String) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Apaga o ficheiro 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 ficheiro a ser eliminado. Não há suporte para caracteres curinga.
Exceções
.NET Framework e .NET Core versões anteriores à 2.1: path é uma cadeia de comprimento zero, contém apenas espaço em branco ou contém um ou mais caracteres inválidos. Pode consultar caracteres inválidos usando o GetInvalidPathChars() método.
path é null.
O caminho especificado é inválido (por exemplo, está num disco não mapeado).
O ficheiro especificado está em uso.
-ou-
Existe um handle aberto no ficheiro, e o sistema operativo é Windows XP ou anterior. Este handle aberto pode resultar da enumeração de diretórios e ficheiros. Para mais informações, veja Como: Enumerar Diretórios e Ficheiros.
path está num formato inválido.
O caminho especificado, nome do ficheiro ou ambos excedem o comprimento máximo definido pelo sistema.
O interlocutor não tem a permissão necessária.
-ou-
O ficheiro é um ficheiro executável que está em uso.
-ou-
path é um diretório.
-ou-
path especificava um ficheiro de apenas leitura.
Exemplos
O exemplo seguinte copia grupos de ficheiros para a pasta de backup C:\archives\2008 e depois elimina-os 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);
}
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
Observações
Especifique um nome de ficheiro com qualquer informação relativa ou absoluta do caminho para o path parâmetro. Personagens coringa não podem ser incluídas. A informação relativa do caminho é interpretada como relativa ao diretório de trabalho atual. Para obter o diretório de trabalho atual, veja GetCurrentDirectory.
Se o ficheiro a eliminar não existir, não é feita nenhuma exceção.
Para uma lista de tarefas comuns de E/S, consulte Tarefas Comuns de E/S.