DirectoryInfo.Delete Método

Definición

Elimina un DirectoryInfo y su contenido de una ruta de acceso.

Sobrecargas

Delete()

Elimina este DirectoryInfo si está vacío.

Delete(Boolean)

Elimina esta instancia de DirectoryInfo, especificando si se van a eliminar los subdirectorios y los archivos.

Delete()

Source:
DirectoryInfo.cs
Source:
DirectoryInfo.cs
Source:
DirectoryInfo.cs

Elimina este DirectoryInfo si está vacío.

public:
 override void Delete();
public override void Delete ();
override this.Delete : unit -> unit
Public Overrides Sub Delete ()

Excepciones

El directorio contiene un archivo de solo lectura.

El directorio que describe este objeto DirectoryInfo no existe o no se ha encontrado.

El directorio no está vacío.

o bien

El directorio es el directorio de trabajo actual de la aplicación.

o bien

Hay un identificador abierto en el directorio, y el sistema operativo es Windows XP o anterior. Este identificador puede obtenerse al enumerar directorios. Para más información, vea Enumeración de directorios y archivos.

El llamador no dispone del permiso requerido.

Ejemplos

En el ejemplo siguiente se produce una excepción si intenta eliminar un directorio que no está vacío.

using namespace System;
using namespace System::IO;
int main()
{
   
   // Specify the directories you want to manipulate.
   DirectoryInfo^ di1 = gcnew DirectoryInfo( "c:\\MyDir" );
   try
   {
      
      // Create the directories.
      di1->Create();
      di1->CreateSubdirectory( "temp" );
      
      //This operation will not be allowed because there are subdirectories.
      Console::WriteLine( "I am about to attempt to delete {0}", di1->Name );
      di1->Delete();
      Console::WriteLine( "The Delete operation was successful, which was unexpected." );
   }
   catch ( Exception^ ) 
   {
      Console::WriteLine( "The Delete operation failed as expected." );
   }

}
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        // Specify the directories you want to manipulate.
        DirectoryInfo di1 = new DirectoryInfo(@"c:\MyDir");

        try
        {
            // Create the directories.
            di1.Create();
            di1.CreateSubdirectory("temp");

            //This operation will not be allowed because there are subdirectories.
            Console.WriteLine("I am about to attempt to delete {0}", di1.Name);
            di1.Delete();
            Console.WriteLine("The Delete operation was successful, which was unexpected.");
        }
        catch (Exception)
        {
            Console.WriteLine("The Delete operation failed as expected.");
        }
        finally {}
    }
}
open System.IO

// Specify the directories you want to manipulate.
let di1 = DirectoryInfo @"c:\MyDir"

try
    // Create the directories.
    di1.Create()
    di1.CreateSubdirectory "temp" |> ignore

    //This operation will not be allowed because there are subdirectories.
    printfn $"I am about to attempt to delete {di1.Name}"
    di1.Delete()
    printfn "The Delete operation was successful, which was unexpected."
with _ ->
    printfn "The Delete operation failed as expected."
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        ' Specify the directories you want to manipulate.
        Dim di1 As DirectoryInfo = New DirectoryInfo("c:\MyDir")

        Try
            ' Create the directories.
            di1.Create()
            di1.CreateSubdirectory("temp")

            'This operation will not be allowed because there are subdirectories.
            Console.WriteLine("I am about to attempt to delete {0}", di1.Name)
            di1.Delete()
            Console.WriteLine("The Delete operation was successful, which was unexpected.")

        Catch
            Console.WriteLine("The Delete operation was unsuccessful, as expected.")
        End Try
    End Sub
End Class

Comentarios

Para obtener una lista de las tareas de E/S comunes, consulte Tareas de E/S comunes.

Consulte también

Se aplica a

Delete(Boolean)

Source:
DirectoryInfo.cs
Source:
DirectoryInfo.cs
Source:
DirectoryInfo.cs

Elimina esta instancia de DirectoryInfo, especificando si se van a eliminar los subdirectorios y los archivos.

public:
 void Delete(bool recursive);
public void Delete (bool recursive);
override this.Delete : bool -> unit
Public Sub Delete (recursive As Boolean)

Parámetros

recursive
Boolean

Es true para eliminar este directorio, sus subdirectorios y todos los archivos; en caso contrario, es false.

Excepciones

El directorio contiene un archivo de solo lectura.

El directorio que describe este objeto DirectoryInfo no existe o no se ha encontrado.

El directorio es de solo lectura.

o bien

El directorio contiene uno o varios archivos o subdirectorios y recursive es false.

o bien

El directorio es el directorio de trabajo actual de la aplicación.

o bien

Hay un identificador abierto en el directorio o en uno de sus archivos, y el sistema operativo es Windows XP o anterior. Este identificador abierto puede obtenerse al enumerar directorios y archivos. Para obtener más información, vea Cómo: Enumerar directorios y archivos.

El llamador no dispone del permiso requerido.

Ejemplos

En el ejemplo siguiente se muestra cómo eliminar un directorio. Dado que se quita el directorio, primero convierta en comentario la Delete línea para probar que el directorio existe. A continuación, quite la marca de comentario de la misma línea de código para probar que el directorio se quitó correctamente.

using namespace System;
using namespace System::IO;
int main()
{
   
   // Make a reference to a directory.
   DirectoryInfo^ di = gcnew DirectoryInfo( "TempDir" );
   
   // Create the directory only if it does not already exist.
   if (  !di->Exists )
      di->Create();

   
   // Create a subdirectory in the directory just created.
   DirectoryInfo^ dis = di->CreateSubdirectory( "SubDir" );
   
   // Process that directory as required.
   // ...
   // Delete the subdirectory. The true indicates that if subdirectories
   // or files are in this directory, they are to be deleted as well.
   dis->Delete( true );
   
   // Delete the directory.
   di->Delete( true );
}
using System;
using System.IO;

public class DeleteTest
{
    public static void Main()
    {

        // Make a reference to a directory.
        DirectoryInfo di = new DirectoryInfo("TempDir");

        // Create the directory only if it does not already exist.
        if (di.Exists == false)
            di.Create();

        // Create a subdirectory in the directory just created.
        DirectoryInfo dis = di.CreateSubdirectory("SubDir");

        // Process that directory as required.
        // ...

        // Delete the subdirectory. The true indicates that if subdirectories
        // or files are in this directory, they are to be deleted as well.
        dis.Delete(true);

        // Delete the directory.
        di.Delete(true);
    }
}
open System.IO

// Make a reference to a directory.
let di = DirectoryInfo "TempDir"

// Create the directory only if it does not already exist.
if not di.Exists then
    di.Create()

// Create a subdirectory in the directory just created.
let dis = di.CreateSubdirectory "SubDir"

// Process that directory as required.
// ...

// Delete the subdirectory. The true indicates that if subdirectories
// or files are in this directory, they are to be deleted as well.
dis.Delete true

// Delete the directory.
di.Delete true
Imports System.IO

Public Class DeleteTest

    Public Shared Sub Main()
        ' Make a reference to a directory.
        Dim di As New DirectoryInfo("TempDir")

        ' Create the directory only if it does not already exist.
        If di.Exists = False Then
            di.Create()
        End If

        Dim dis As DirectoryInfo = di.CreateSubdirectory("SubDir")
        ' Create a subdirectory in the directory just created.

        ' Process that directory as required.
        ' ...

        ' Delete the subdirectory. The true indicates that if subdirectories
        ' or files are in this directory, they are to be deleted as well.
        dis.Delete(True)

        ' Delete the directory.
        di.Delete(True)
    End Sub
End Class

Comentarios

Si no DirectoryInfo tiene archivos o subdirectorios, este método elimina incluso DirectoryInfo si recursive es false. Intentando eliminar un que DirectoryInfo no está vacío cuando recursive se false produce una IOExceptionexcepción .

Para obtener una lista de las tareas de E/S comunes, consulte Tareas de E/S comunes.

Consulte también

Se aplica a