Share via


DirectoryInfo(String) Construtor

Definição

Inicializa uma nova instância da classe DirectoryInfo no caminho especificado.

public:
 DirectoryInfo(System::String ^ path);
public DirectoryInfo (string path);
new System.IO.DirectoryInfo : string -> System.IO.DirectoryInfo
Public Sub New (path As String)

Parâmetros

path
String

Uma cadeia de caracteres que especifica o caminho no qual criar o DirectoryInfo.

Exceções

path é null.

O chamador não tem a permissão necessária.

.NET Framework e versões do .NET Core anteriores à 2.1: path contém caracteres inválidos, como ", <, >ou |.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.

Exemplos

O exemplo a seguir usa esse construtor para criar o diretório e o subdiretório especificados e demonstra que um diretório que contém subdiretórios não pode ser excluído.

using namespace System;
using namespace System::IO;
int main()
{
   
   // Specify the directories you want to manipulate.
   DirectoryInfo^ di1 = gcnew DirectoryInfo( "c:\\MyDir" );
   DirectoryInfo^ di2 = gcnew DirectoryInfo( "c:\\MyDir\\temp" );
   try
   {
      
      // Create the directories.
      di1->Create();
      di2->Create();
      
      // 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");
        DirectoryInfo di2 = new DirectoryInfo(@"c:\MyDir\temp");

        try
        {
            // Create the directories.
            di1.Create();
            di2.Create();

            // 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"
let di2 = DirectoryInfo @"c:\MyDir\temp"

try
    // Create the directories.
    di1.Create()
    di2.Create()

    // 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")
        Dim di2 As DirectoryInfo = New DirectoryInfo("c:\MyDir\temp")
        Try
            ' Create the directories.
            di1.Create()
            di2.Create()
            ' 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 e As Exception
            Console.WriteLine("The Delete operation failed as expected.")
        End Try
    End Sub
End Class

Comentários

Esse construtor não marcar se houver um diretório. Esse construtor é um espaço reservado para uma cadeia de caracteres que é usada para acessar o disco em operações subsequentes.

O path parâmetro pode ser um nome de arquivo, incluindo um arquivo em um compartilhamento UNC (Convenção Universal de Nomenclatura).

Cuidado

Quando você compila um conjunto de caracteres com uma configuração cultural específica e recupera esses mesmos caracteres com uma configuração cultural diferente, os caracteres podem não ser interpretáveis e podem fazer com que uma exceção seja gerada.

Para obter uma lista de tarefas comuns de E/S, consulte Tarefas comuns de E/S.

Aplica-se a

Confira também