Directory.GetDirectories Método

Definição

Retorna os nomes de subdiretórios que atendem ao critério especificado.Returns the names of subdirectories that meet specified criteria.

Sobrecargas

GetDirectories(String, String, SearchOption)

Retorna os nomes dos subdiretórios (incluindo os caminhos) que correspondem ao padrão de pesquisa especificado no diretório especificado e, opcionalmente, subdiretórios de pesquisas.Returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories.

GetDirectories(String, String, EnumerationOptions)

Retorna os nomes de subdiretórios (incluindo os caminhos) que correspondem às opções de enumeração e ao padrão de pesquisa especificados no diretório especificado.Returns the names of subdirectories (including their paths) that match the specified search pattern and enumeration options in the specified directory.

GetDirectories(String)

Retorna os nomes de subdiretórios (inclusive os caminhos) no diretório especificado.Returns the names of subdirectories (including their paths) in the specified directory.

GetDirectories(String, String)

Retorna os nomes de subdiretórios (incluindo os caminhos) que correspondem ao padrão de pesquisa especificado no diretório especificado.Returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory.

GetDirectories(String, String, SearchOption)

Retorna os nomes dos subdiretórios (incluindo os caminhos) que correspondem ao padrão de pesquisa especificado no diretório especificado e, opcionalmente, subdiretórios de pesquisas.Returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories.

public:
 static cli::array <System::String ^> ^ GetDirectories(System::String ^ path, System::String ^ searchPattern, System::IO::SearchOption searchOption);
public static string[] GetDirectories (string path, string searchPattern, System.IO.SearchOption searchOption);
static member GetDirectories : string * string * System.IO.SearchOption -> string[]
Public Shared Function GetDirectories (path As String, searchPattern As String, searchOption As SearchOption) As String()

Parâmetros

path
String

O caminho relativo ou absoluto para o diretório a ser pesquisado.The relative or absolute path to the directory to search. Esta cadeia de caracteres não diferencia maiúsculas de minúsculas.This string is not case-sensitive.

searchPattern
String

A cadeia de caracteres de pesquisa para correspondência com os nomes dos subdiretórios em path.The search string to match against the names of subdirectories in path. Esse parâmetro pode conter uma combinação de caracteres literais e curinga válidos, mas não dá suporte a expressões regulares.This parameter can contain a combination of valid literal and wildcard characters, but it doesn't support regular expressions.

searchOption
SearchOption

Um dos valores de enumeração que especifica se a operação de pesquisa deve incluir todos os subdiretórios ou apenas o diretório atual.One of the enumeration values that specifies whether the search operation should include all subdirectories or only the current directory.

Retornos

String[]

Uma matriz de nomes completos (incluindo caminhos) dos subdiretórios que correspondem aos critérios especificados, ou uma matriz vazia, se nenhum diretório for encontrado.An array of the full names (including paths) of the subdirectories that match the specified criteria, or an empty array if no directories are found.

Exceções

path é uma cadeia de comprimento zero, contém somente espaços em branco ou um ou mais caracteres inválidos.path is a zero-length string, contains only white space, or contains one or more invalid characters. Consulte caracteres inválidos usando o método GetInvalidPathChars().You can query for invalid characters by using the GetInvalidPathChars() method.

- ou --or- searchPattern não contém um padrão válido.searchPattern does not contain a valid pattern.

path ou searchPattern é null.path or searchPattern is null.

searchOption não é um valor SearchOption válido.searchOption is not a valid SearchOption value.

O chamador não tem a permissão necessária.The caller does not have the required permission.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.

path é um nome de arquivo.path is a file name.

O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).

Exemplos

O exemplo a seguir conta o número de diretórios que começam com a letra especificada em um caminho.The following example counts the number of directories that begin with the specified letter in a path. Somente o diretório de nível superior é pesquisado.Only the top-level directory is searched.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            string[] dirs = Directory.GetDirectories(@"c:\", "p*", SearchOption.TopDirectoryOnly);
            Console.WriteLine("The number of directories starting with p is {0}.", dirs.Length);
            foreach (string dir in dirs)
            {
                Console.WriteLine(dir);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        Try
            Dim dirs As String() = Directory.GetDirectories("c:\", "p*", SearchOption.TopDirectoryOnly)
            Console.WriteLine("The number of directories starting with p is {0}.", dirs.Length)
            Dim dir As String
            For Each dir In dirs
                Console.WriteLine(dir)
            Next
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Comentários

O path parâmetro pode especificar informações de caminho relativo ou absoluto e não diferencia maiúsculas de minúsculas.The path parameter can specify relative or absolute path information, and is not case-sensitive. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual.Relative path information is interpreted as relative to the current working directory. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory .To obtain the current working directory, see GetCurrentDirectory.

searchPattern pode ser uma combinação de caracteres literais e curinga, mas não oferece suporte a expressões regulares.searchPattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. Os especificadores curinga a seguir são permitidos no searchPattern .The following wildcard specifiers are permitted in searchPattern.

Especificador de curingaWildcard specifier Corresponde aMatches
* asterisco* (asterisk) Zero ou mais caracteres nessa posição.Zero or more characters in that position.
?? (ponto de interrogação)(question mark) Zero ou um caractere nessa posição.Zero or one character in that position.

Caracteres diferentes do curinga são caracteres literais.Characters other than the wildcard are literal characters. Por exemplo, a searchPattern cadeia de caracteres " * t" procura todos os nomes path que terminam com a letra "t".For example, the searchPattern string "*t" searches for all names in path ending with the letter "t". A searchPattern cadeia de caracteres "s * " pesquisa todos os nomes no path início com a letra "s".The searchPattern string "s*" searches for all names in path beginning with the letter "s".

searchPattern Não pode terminar em dois pontos ("..") ou conter dois pontos ("..") seguidos por DirectorySeparatorChar ou AltDirectorySeparatorChar , nem pode conter caracteres inválidos.searchPattern cannot end in two periods ("..") or contain two periods ("..") followed by DirectorySeparatorChar or AltDirectorySeparatorChar, nor can it contain any invalid characters. Consulte caracteres inválidos usando o método GetInvalidPathChars.You can query for invalid characters by using the GetInvalidPathChars method.

Os EnumerateDirectories GetDirectories métodos e são diferentes da seguinte maneira: ao usar o EnumerateDirectories , você pode iniciar a enumeração da coleção de nomes antes que toda a coleção seja retornada; ao usar GetDirectories o, você deve aguardar até que toda a matriz de nomes seja retornada antes de poder acessar a matriz.The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. Portanto, quando você estiver trabalhando com muitos arquivos e diretórios, o EnumerateDirectories poderá ser mais eficiente.Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Confira também

Aplica-se a

GetDirectories(String, String, EnumerationOptions)

Retorna os nomes de subdiretórios (incluindo os caminhos) que correspondem às opções de enumeração e ao padrão de pesquisa especificados no diretório especificado.Returns the names of subdirectories (including their paths) that match the specified search pattern and enumeration options in the specified directory.

public:
 static cli::array <System::String ^> ^ GetDirectories(System::String ^ path, System::String ^ searchPattern, System::IO::EnumerationOptions ^ enumerationOptions);
public static string[] GetDirectories (string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions);
static member GetDirectories : string * string * System.IO.EnumerationOptions -> string[]
Public Shared Function GetDirectories (path As String, searchPattern As String, enumerationOptions As EnumerationOptions) As String()

Parâmetros

path
String

O caminho relativo ou absoluto para o diretório a ser pesquisado.The relative or absolute path to the directory to search. Esta cadeia de caracteres não diferencia maiúsculas de minúsculas.This string is not case-sensitive.

searchPattern
String

A cadeia de caracteres de pesquisa para correspondência com os nomes dos subdiretórios em path.The search string to match against the names of subdirectories in path. Esse parâmetro pode conter uma combinação de caracteres literais e curinga válidos, mas não dá suporte a expressões regulares.This parameter can contain a combination of valid literal and wildcard characters, but it doesn't support regular expressions.

enumerationOptions
EnumerationOptions

Um objeto que descreve a configuração de pesquisa e enumeração a ser usada.An object that describes the search and enumeration configuration to use.

Retornos

String[]

Uma matriz de nomes completos (incluindo caminhos) dos subdiretórios que correspondem ao padrão de pesquisa e às opções de enumeração no diretório especificado ou uma matriz vazia, se nenhum diretório foi encontrado.An array of the full names (including paths) of the subdirectories that match the search pattern and enumeration options in the specified directory, or an empty array if no directories are found.

Exceções

O chamador não tem a permissão necessária.The caller does not have the required permission.

path é uma cadeia de comprimento zero, contém somente espaços em branco ou um ou mais caracteres inválidos.path is a zero-length string, contains only white space, or contains one or more invalid characters. É possível consultar caracteres inválidos usando GetInvalidPathChars().You can query for invalid characters by using GetInvalidPathChars().

- ou --or- searchPattern não contém um padrão válido.searchPattern doesn't contain a valid pattern.

path ou searchPattern é null.path or searchPattern is null.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.

path é um nome de arquivo.path is a file name.

O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).

Comentários

Esse método retorna todos os subdiretórios diretamente sob o diretório especificado que correspondem ao padrão de pesquisa especificado.This method returns all subdirectories directly under the specified directory that match the specified search pattern. Se o diretório especificado não tiver subdiretórios ou nenhum subdiretório corresponder ao searchPattern parâmetro, esse método retornará uma matriz vazia.If the specified directory has no subdirectories, or no subdirectories match the searchPattern parameter, this method returns an empty array. Somente o diretório superior é pesquisado.Only the top directory is searched. Se você quiser pesquisar os subdiretórios também, use o GetDirectories(String, String, SearchOption) método e especifique AllDirectories no searchOption parâmetro.If you want to search the subdirectories as well, use the GetDirectories(String, String, SearchOption) method and specify AllDirectories in the searchOption parameter.

searchPattern pode ser uma combinação de caracteres literais e curinga, mas não oferece suporte a expressões regulares.searchPattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. Os especificadores curinga a seguir são permitidos no searchPattern .The following wildcard specifiers are permitted in searchPattern.

Especificador de curingaWildcard specifier Corresponde aMatches
* asterisco* (asterisk) Zero ou mais caracteres nessa posição.Zero or more characters in that position.
?? (ponto de interrogação)(question mark) Zero ou um caractere nessa posição.Zero or one character in that position.

Caracteres diferentes do curinga são caracteres literais.Characters other than the wildcard are literal characters. Por exemplo, a searchPattern cadeia de caracteres " * t" procura todos os nomes path que terminam com a letra "t".For example, the searchPattern string "*t" searches for all names in path ending with the letter "t". A searchPattern cadeia de caracteres "s * " pesquisa todos os nomes no path início com a letra "s".The searchPattern string "s*" searches for all names in path beginning with the letter "s".

searchPattern Não pode terminar em dois pontos ("..") ou conter dois pontos ("..") seguidos por DirectorySeparatorChar ou AltDirectorySeparatorChar , nem pode conter caracteres inválidos.searchPattern cannot end in two periods ("..") or contain two periods ("..") followed by DirectorySeparatorChar or AltDirectorySeparatorChar, nor can it contain any invalid characters. Consulte caracteres inválidos usando o método GetInvalidPathChars.You can query for invalid characters by using the GetInvalidPathChars method.

O path parâmetro pode especificar informações de caminho relativo ou absoluto e não diferencia maiúsculas de minúsculas.The path parameter can specify relative or absolute path information, and is not case-sensitive. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual.Relative path information is interpreted as relative to the current working directory. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory .To obtain the current working directory, see GetCurrentDirectory.

Os EnumerateDirectories GetDirectories métodos e são diferentes da seguinte maneira: ao usar o EnumerateDirectories , você pode iniciar a enumeração da coleção de nomes antes que toda a coleção seja retornada; ao usar GetDirectories o, você deve aguardar até que toda a matriz de nomes seja retornada antes de poder acessar a matriz.The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. Portanto, quando você estiver trabalhando com muitos arquivos e diretórios, o EnumerateDirectories poderá ser mais eficiente.Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Aplica-se a

GetDirectories(String)

Retorna os nomes de subdiretórios (inclusive os caminhos) no diretório especificado.Returns the names of subdirectories (including their paths) in the specified directory.

public:
 static cli::array <System::String ^> ^ GetDirectories(System::String ^ path);
public static string[] GetDirectories (string path);
static member GetDirectories : string -> string[]
Public Shared Function GetDirectories (path As String) As String()

Parâmetros

path
String

O caminho relativo ou absoluto para o diretório a ser pesquisado.The relative or absolute path to the directory to search. Esta cadeia de caracteres não diferencia maiúsculas de minúsculas.This string is not case-sensitive.

Retornos

String[]

Uma matriz de nomes completos (incluindo caminhos) dos subdiretórios no caminho especificado, ou uma matriz vazia, se nenhum diretório for encontrado.An array of the full names (including paths) of subdirectories in the specified path, or an empty array if no directories are found.

Exceções

O chamador não tem a permissão necessária.The caller does not have the required permission.

path é uma cadeia de comprimento zero, contém somente espaços em branco ou um ou mais caracteres inválidos.path is a zero-length string, contains only white space, or contains one or more invalid characters. Consulte caracteres inválidos usando o método GetInvalidPathChars().You can query for invalid characters by using the GetInvalidPathChars() method.

path é null.path is null.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.

path é um nome de arquivo.path is a file name.

O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).

Exemplos

O exemplo a seguir usa uma matriz de nomes de arquivo ou diretório na linha de comando, determina o tipo de nome que ele é e o processa adequadamente.The following example takes an array of file or directory names on the command line, determines what kind of name it is, and processes it appropriately.

// For Directory::GetFiles and Directory::GetDirectories
// For File::Exists, Directory::Exists
using namespace System;
using namespace System::IO;
using namespace System::Collections;

// Insert logic for processing found files here.
void ProcessFile( String^ path )
{
   Console::WriteLine( "Processed file '{0}'.", path );
}


// Process all files in the directory passed in, recurse on any directories 
// that are found, and process the files they contain.
void ProcessDirectory( String^ targetDirectory )
{
   
   // Process the list of files found in the directory.
   array<String^>^fileEntries = Directory::GetFiles( targetDirectory );
   IEnumerator^ files = fileEntries->GetEnumerator();
   while ( files->MoveNext() )
   {
      String^ fileName = safe_cast<String^>(files->Current);
      ProcessFile( fileName );
   }

   
   // Recurse into subdirectories of this directory.
   array<String^>^subdirectoryEntries = Directory::GetDirectories( targetDirectory );
   IEnumerator^ dirs = subdirectoryEntries->GetEnumerator();
   while ( dirs->MoveNext() )
   {
      String^ subdirectory = safe_cast<String^>(dirs->Current);
      ProcessDirectory( subdirectory );
   }
}

int main( int argc, char *argv[] )
{
   for ( int i = 1; i < argc; i++ )
   {
      String^ path = gcnew String(argv[ i ]);
      if ( File::Exists( path ) )
      {
         
         // This path is a file
         ProcessFile( path );
      }
      else
      if ( Directory::Exists( path ) )
      {
         
         // This path is a directory
         ProcessDirectory( path );
      }
      else
      {
         Console::WriteLine( "{0} is not a valid file or directory.", path );
      }

   }
}

// For Directory.GetFiles and Directory.GetDirectories
// For File.Exists, Directory.Exists
using System;
using System.IO;
using System.Collections;

public class RecursiveFileProcessor
{
    public static void Main(string[] args)
    {
        foreach(string path in args)
        {
            if(File.Exists(path))
            {
                // This path is a file
                ProcessFile(path);
            }
            else if(Directory.Exists(path))
            {
                // This path is a directory
                ProcessDirectory(path);
            }
            else
            {
                Console.WriteLine("{0} is not a valid file or directory.", path);
            }
        }
    }

    // Process all files in the directory passed in, recurse on any directories
    // that are found, and process the files they contain.
    public static void ProcessDirectory(string targetDirectory)
    {
        // Process the list of files found in the directory.
        string [] fileEntries = Directory.GetFiles(targetDirectory);
        foreach(string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory.
        string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach(string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }

    // Insert logic for processing found files here.
    public static void ProcessFile(string path)
    {
        Console.WriteLine("Processed file '{0}'.", path);	
    }
}
' For Directory.GetFiles and Directory.GetDirectories
' For File.Exists, Directory.Exists 

Imports System.IO
Imports System.Collections

Public Class RecursiveFileProcessor

    Public Overloads Shared Sub Main(ByVal args() As String)
        Dim path As String
        For Each path In args
            If File.Exists(path) Then
                ' This path is a file.
                ProcessFile(path)
            Else
                If Directory.Exists(path) Then
                    ' This path is a directory.
                    ProcessDirectory(path)
                Else
                    Console.WriteLine("{0} is not a valid file or directory.", path)
                End If
            End If
        Next path
    End Sub


    ' Process all files in the directory passed in, recurse on any directories 
    ' that are found, and process the files they contain.
    Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
        Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
        ' Process the list of files found in the directory.
        Dim fileName As String
        For Each fileName In fileEntries
            ProcessFile(fileName)

        Next fileName
        Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
        ' Recurse into subdirectories of this directory.
        Dim subdirectory As String
        For Each subdirectory In subdirectoryEntries
            ProcessDirectory(subdirectory)
        Next subdirectory

    End Sub

    ' Insert logic for processing found files here.
    Public Shared Sub ProcessFile(ByVal path As String)
        Console.WriteLine("Processed file '{0}'.", path)
    End Sub
End Class

Comentários

Esse método é idêntico ao GetDirectories(String, String) asterisco ( * ) especificado como o padrão de pesquisa, portanto, retorna todos os subdiretórios.This method is identical to GetDirectories(String, String) with the asterisk (*) specified as the search pattern, so it returns all subdirectories. Se você precisar pesquisar subdiretórios, use o GetDirectories(String, String, SearchOption) método, que permite especificar uma pesquisa de subdiretórios com o searchOption parâmetro.If you need to search subdirectories, use the GetDirectories(String, String, SearchOption) method, which enables you to specify a search of subdirectories with the searchOption parameter.

Os EnumerateDirectories GetDirectories métodos e são diferentes da seguinte maneira: ao usar o EnumerateDirectories , você pode iniciar a enumeração da coleção de nomes antes que toda a coleção seja retornada; ao usar GetDirectories o, você deve aguardar até que toda a matriz de nomes seja retornada antes de poder acessar a matriz.The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. Portanto, quando você estiver trabalhando com muitos arquivos e diretórios, o EnumerateDirectories poderá ser mais eficiente.Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

O path parâmetro pode especificar informações de caminho relativo ou absoluto.The path parameter can specify relative or absolute path information. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual.Relative path information is interpreted as relative to the current working directory. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory .To obtain the current working directory, see GetCurrentDirectory.

Os nomes retornados por esse método são prefixados com as informações de diretório fornecidas no path .The names returned by this method are prefixed with the directory information provided in path.

O path parâmetro não diferencia maiúsculas de minúsculas.The path parameter is not case-sensitive.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Confira também

Aplica-se a

GetDirectories(String, String)

Retorna os nomes de subdiretórios (incluindo os caminhos) que correspondem ao padrão de pesquisa especificado no diretório especificado.Returns the names of subdirectories (including their paths) that match the specified search pattern in the specified directory.

public:
 static cli::array <System::String ^> ^ GetDirectories(System::String ^ path, System::String ^ searchPattern);
public static string[] GetDirectories (string path, string searchPattern);
static member GetDirectories : string * string -> string[]
Public Shared Function GetDirectories (path As String, searchPattern As String) As String()

Parâmetros

path
String

O caminho relativo ou absoluto para o diretório a ser pesquisado.The relative or absolute path to the directory to search. Esta cadeia de caracteres não diferencia maiúsculas de minúsculas.This string is not case-sensitive.

searchPattern
String

A cadeia de caracteres de pesquisa para correspondência com os nomes dos subdiretórios em path.The search string to match against the names of subdirectories in path. Esse parâmetro pode conter uma combinação de caracteres literais e curinga válidos, mas não dá suporte a expressões regulares.This parameter can contain a combination of valid literal and wildcard characters, but it doesn't support regular expressions.

Retornos

String[]

Uma matriz de nomes completos (incluindo caminhos) dos subdiretórios que correspondem ao padrão de pesquisa no diretório especificado, ou uma matriz vazia, se nenhum diretório for encontrado.An array of the full names (including paths) of the subdirectories that match the search pattern in the specified directory, or an empty array if no directories are found.

Exceções

O chamador não tem a permissão necessária.The caller does not have the required permission.

path é uma cadeia de comprimento zero, contém somente espaços em branco ou um ou mais caracteres inválidos.path is a zero-length string, contains only white space, or contains one or more invalid characters. É possível consultar caracteres inválidos usando GetInvalidPathChars().You can query for invalid characters by using GetInvalidPathChars().

- ou --or- searchPattern não contém um padrão válido.searchPattern doesn't contain a valid pattern.

path ou searchPattern é null.path or searchPattern is null.

O caminho especificado, o nome de arquivo, ou ambos excedem o tamanho máximo definido pelo sistema.The specified path, file name, or both exceed the system-defined maximum length.

path é um nome de arquivo.path is a file name.

O caminho especificado é inválido (por exemplo, ele está em uma unidade não mapeada).The specified path is invalid (for example, it is on an unmapped drive).

Exemplos

O exemplo a seguir conta o número de diretórios em um caminho que começam com a letra especificada.The following example counts the number of directories in a path that begin with the specified letter.

using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      
      // Only get subdirectories that begin with the letter "p."
      array<String^>^dirs = Directory::GetDirectories( "c:\\", "p*" );
      Console::WriteLine( "The number of directories starting with p is {0}.", dirs->Length );
      Collections::IEnumerator^ myEnum = dirs->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         Console::WriteLine( myEnum->Current );
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }

}

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            // Only get subdirectories that begin with the letter "p."
            string[] dirs = Directory.GetDirectories(@"c:\", "p*");
            Console.WriteLine("The number of directories starting with p is {0}.", dirs.Length);
            foreach (string dir in dirs)
            {
                Console.WriteLine(dir);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        Try
            ' Only get subdirectories that begin with the letter "p."
            Dim dirs As String() = Directory.GetDirectories("c:\", "p*")
            Console.WriteLine("The number of directories starting with p is {0}.", dirs.Length)
            Dim dir As String
            For Each dir In dirs
                Console.WriteLine(dir)
            Next
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Comentários

Esse método retorna todos os subdiretórios diretamente sob o diretório especificado que correspondem ao padrão de pesquisa especificado.This method returns all subdirectories directly under the specified directory that match the specified search pattern. Se o diretório especificado não tiver subdiretórios ou nenhum subdiretório corresponder ao searchPattern parâmetro, esse método retornará uma matriz vazia.If the specified directory has no subdirectories, or no subdirectories match the searchPattern parameter, this method returns an empty array. Somente o diretório superior é pesquisado.Only the top directory is searched. Se você quiser pesquisar os subdiretórios também, use o GetDirectories(String, String, SearchOption) método e especifique AllDirectories no searchOption parâmetro.If you want to search the subdirectories as well, use the GetDirectories(String, String, SearchOption) method and specify AllDirectories in the searchOption parameter.

searchPattern pode ser uma combinação de caracteres literais e curinga, mas não oferece suporte a expressões regulares.searchPattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. Os especificadores curinga a seguir são permitidos no searchPattern .The following wildcard specifiers are permitted in searchPattern.

Especificador de curingaWildcard specifier Corresponde aMatches
* asterisco* (asterisk) Zero ou mais caracteres nessa posição.Zero or more characters in that position.
?? (ponto de interrogação)(question mark) Zero ou um caractere nessa posição.Zero or one character in that position.

Caracteres diferentes do curinga são caracteres literais.Characters other than the wildcard are literal characters. Por exemplo, a searchPattern cadeia de caracteres " * t" procura todos os nomes path que terminam com a letra "t".For example, the searchPattern string "*t" searches for all names in path ending with the letter "t". A searchPattern cadeia de caracteres "s * " pesquisa todos os nomes no path início com a letra "s".The searchPattern string "s*" searches for all names in path beginning with the letter "s".

searchPattern Não pode terminar em dois pontos ("..") ou conter dois pontos ("..") seguidos por DirectorySeparatorChar ou AltDirectorySeparatorChar , nem pode conter caracteres inválidos.searchPattern cannot end in two periods ("..") or contain two periods ("..") followed by DirectorySeparatorChar or AltDirectorySeparatorChar, nor can it contain any invalid characters. Consulte caracteres inválidos usando o método GetInvalidPathChars.You can query for invalid characters by using the GetInvalidPathChars method.

O path parâmetro pode especificar informações de caminho relativo ou absoluto e não diferencia maiúsculas de minúsculas.The path parameter can specify relative or absolute path information, and is not case-sensitive. As informações do caminho relativo são interpretadas como relativas ao diretório de trabalho atual.Relative path information is interpreted as relative to the current working directory. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory .To obtain the current working directory, see GetCurrentDirectory.

Os EnumerateDirectories GetDirectories métodos e são diferentes da seguinte maneira: ao usar o EnumerateDirectories , você pode iniciar a enumeração da coleção de nomes antes que toda a coleção seja retornada; ao usar GetDirectories o, você deve aguardar até que toda a matriz de nomes seja retornada antes de poder acessar a matriz.The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. Portanto, quando você estiver trabalhando com muitos arquivos e diretórios, o EnumerateDirectories poderá ser mais eficiente.Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

Para obter uma lista de tarefas comuns de e/s, consulte tarefas comuns de e/s.For a list of common I/O tasks, see Common I/O Tasks.

Confira também

Aplica-se a