DirectoryInfo.EnumerateDirectories 方法

定义

返回当前目录中目录信息的可枚举集合。Returns an enumerable collection of directory information in the current directory.

重载

EnumerateDirectories(String, SearchOption)

返回与指定的搜索模式和搜索子目录选项匹配的目录信息的可枚举集合。Returns an enumerable collection of directory information that matches a specified search pattern and search subdirectory option.

EnumerateDirectories(String, EnumerationOptions)

返回与指定的搜索模式和枚举选项匹配的目录信息的可枚举集合。Returns an enumerable collection of directory information that matches the specified search pattern and enumeration options.

EnumerateDirectories()

返回当前目录中目录信息的可枚举集合。Returns an enumerable collection of directory information in the current directory.

EnumerateDirectories(String)

返回与指定的搜索模式匹配的目录信息的可枚举集合。Returns an enumerable collection of directory information that matches a specified search pattern.

EnumerateDirectories(String, SearchOption)

返回与指定的搜索模式和搜索子目录选项匹配的目录信息的可枚举集合。Returns an enumerable collection of directory information that matches a specified search pattern and search subdirectory option.

public:
 System::Collections::Generic::IEnumerable<System::IO::DirectoryInfo ^> ^ EnumerateDirectories(System::String ^ searchPattern, System::IO::SearchOption searchOption);
public System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo> EnumerateDirectories (string searchPattern, System.IO.SearchOption searchOption);
member this.EnumerateDirectories : string * System.IO.SearchOption -> seq<System.IO.DirectoryInfo>
Public Function EnumerateDirectories (searchPattern As String, searchOption As SearchOption) As IEnumerable(Of DirectoryInfo)

参数

searchPattern
String

要与目录名匹配的搜索字符串。The search string to match against the names of directories. 此参数可以包含有效文本路径和通配符(* 和 ?)的组合,但不支持正则表达式。This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.

searchOption
SearchOption

指定搜索操作是应仅包含当前目录还是应包含所有子目录的枚举值之一。One of the enumeration values that specifies whether the search operation should include only the current directory or all subdirectories. 默认值为 TopDirectoryOnlyThe default value is TopDirectoryOnly.

返回

searchPatternsearchOption 匹配的目录的可枚举集合。An enumerable collection of directories that matches searchPattern and searchOption.

例外

searchPatternnullsearchPattern is null.

searchOption 不是有效的 SearchOption 值。searchOption is not a valid SearchOption value.

封装在 DirectoryInfo 对象中的路径无效(例如,在未映射的驱动器上)。The path encapsulated in the DirectoryInfo object is invalid (for example, it is on an unmapped drive).

调用方没有所要求的权限。The caller does not have the required permission.

示例

下面的示例从指定目录开始,使用此方法和 EnumerateFiles 方法来枚举开始目录内的文件和目录,并显示大小超过 10 MB 的任何文件的详细信息。The following example, starting from a specified directory, uses this method and the EnumerateFiles method to enumerate the files and directories within the start directory and display details of any files over 10 MB in size.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // Set a variable to the My Documents path.
        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        DirectoryInfo diTop = new DirectoryInfo(docPath);

        try
        {
            foreach (var fi in diTop.EnumerateFiles())
            {
                try
                {
                    // Display each file over 10 MB;
                    if (fi.Length > 10000000)
                    {
                        Console.WriteLine($"{fi.FullName}\t\t{fi.Length.ToString("NO")}");
                    }
                }
                catch (UnauthorizedAccessException unAuthTop)
                {
                    Console.WriteLine($"{unAuthTop.Message}");
                }
            }
            
            foreach (var di in diTop.EnumerateDirectories("*"))
            {
                try
                {
                    foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
                    {
                        try
                        {
                            // Display each file over 10 MB;
                            if (fi.Length > 10000000)
                            {
                                Console.WriteLine($"{fi.FullName}\t\t{fi.Length.ToString("NO")}");
                            }
                        }
                        catch (UnauthorizedAccessException unAuthFile)
                        {
                            Console.WriteLine($"unAuthFile: {unAuthFile.Message}");
                        }
                    }
                }
                catch (UnauthorizedAccessException unAuthSubDir)
                {
                    Console.WriteLine($"unAuthSubDir: {unAuthSubDir.Message}");
                }
            }
        }
        catch (DirectoryNotFoundException dirNotFound)
        {
            Console.WriteLine($"{dirNotFound.Message}");
        }
        catch (UnauthorizedAccessException unAuthDir)
        {
            Console.WriteLine($"unAuthDir: {unAuthDir.Message}");
        }
        catch (PathTooLongException longPath)
        {
            Console.WriteLine($"{longPath.Message}");
        }
    }
}
Imports System.IO

Class Program
    Public Shared Sub Main(ByVal args As String())
        Dim dirPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        Dim diTop As New DirectoryInfo(dirPath)
        Try
            For Each fi In diTop.EnumerateFiles()
                Try
                    ' Display each file over 10 MB;
                    If fi.Length > 10000000 Then
                        Console.WriteLine("{0}" & vbTab & vbTab & "{1}", fi.FullName, fi.Length.ToString("N0"))
                    End If
                Catch unAuthTop As UnauthorizedAccessException
                    Console.WriteLine($"{unAuthTop.Message}")
                End Try
            Next

            For Each di In diTop.EnumerateDirectories("*")
                Try
                    For Each fi In di.EnumerateFiles("*", SearchOption.AllDirectories)
                        Try
                            ' // Display each file over 10 MB;
                            If fi.Length > 10000000 Then
                                Console.WriteLine("{0}" & vbTab &
                                vbTab & "{1}", fi.FullName, fi.Length.ToString("N0"))
                            End If
                        Catch unAuthFile As UnauthorizedAccessException
                            Console.WriteLine($"unAuthFile: {unAuthFile.Message}")
                        End Try
                    Next
                Catch unAuthSubDir As UnauthorizedAccessException
                    Console.WriteLine($"unAuthSubDir: {unAuthSubDir.Message}")
                End Try
            Next
        Catch dirNotFound As DirectoryNotFoundException
            Console.WriteLine($"{dirNotFound.Message}")
        Catch unAuthDir As UnauthorizedAccessException
            Console.WriteLine($"unAuthDir: {unAuthDir.Message}")
        Catch longPath As PathTooLongException
            Console.WriteLine($"{longPath.Message}")
        End Try
    End Sub
End Class

注解

searchPattern 可以是文字和通配符的组合,但不支持正则表达式。searchPattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. searchPattern中允许使用以下通配符说明符。The following wildcard specifiers are permitted in searchPattern.

通配符说明符Wildcard specifier 匹配Matches
* (星号)* (asterisk) 此位置中的零个或多个字符。Zero or more characters in that position.
?? (问号)(question mark) 此位置中的零个或一个字符。Zero or one character in that position.

通配符以外的字符为原义字符。Characters other than the wildcard are literal characters. 例如,字符串 "*t" 搜索以字母 "t" 结尾的所有名称。For example, the string "*t" searches for all names in ending with the letter "t". ".". searchPattern 字符串 "s*" 搜索 path 以字母 "s" 开头的所有名称。The searchPattern string "s*" searches for all names in path beginning with the letter "s".

EnumerateDirectoriesGetDirectories 方法的区别如下:The EnumerateDirectories and GetDirectories methods differ as follows:

因此,在处理多个文件和目录时,EnumerateDirectories 可能更高效。Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

此方法预先填充以下 DirectoryInfo 属性的值:This method pre-populates the values of the following DirectoryInfo properties:

未缓存返回的集合;对集合的 GetEnumerator 方法的每个调用都将开始一个新的枚举。The returned collection is not cached; each call to the GetEnumerator method on the collection will start a new enumeration.

EnumerateDirectories(String, EnumerationOptions)

返回与指定的搜索模式和枚举选项匹配的目录信息的可枚举集合。Returns an enumerable collection of directory information that matches the specified search pattern and enumeration options.

public:
 System::Collections::Generic::IEnumerable<System::IO::DirectoryInfo ^> ^ EnumerateDirectories(System::String ^ searchPattern, System::IO::EnumerationOptions ^ enumerationOptions);
public System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo> EnumerateDirectories (string searchPattern, System.IO.EnumerationOptions enumerationOptions);
member this.EnumerateDirectories : string * System.IO.EnumerationOptions -> seq<System.IO.DirectoryInfo>
Public Function EnumerateDirectories (searchPattern As String, enumerationOptions As EnumerationOptions) As IEnumerable(Of DirectoryInfo)

参数

searchPattern
String

要与目录名匹配的搜索字符串。The search string to match against the names of directories. 此参数可以包含有效文本路径和通配符(* 和 ?)的组合,但不支持正则表达式。This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.

enumerationOptions
EnumerationOptions

描述要使用的搜索和枚举配置的对象。An object that describes the search and enumeration configuration to use.

返回

searchPatternenumerationOptions 匹配的目录的可枚举集合。An enumerable collection of directories that matches searchPattern and enumerationOptions.

例外

searchPatternnullsearchPattern is null.

封装在 DirectoryInfo 对象中的路径无效(例如,在未映射的驱动器上)。The path encapsulated in the DirectoryInfo object is invalid (for example, it is on an unmapped drive).

调用方没有所要求的权限。The caller does not have the required permission.

注解

searchPattern 可以是文字和通配符的组合,但不支持正则表达式。searchPattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. searchPattern中允许使用以下通配符说明符。The following wildcard specifiers are permitted in searchPattern.

通配符说明符Wildcard specifier 匹配Matches
* (星号)* (asterisk) 此位置中的零个或多个字符。Zero or more characters in that position.
?? (问号)(question mark) 此位置中的零个或一个字符。Zero or one character in that position.

通配符以外的字符为原义字符。Characters other than the wildcard are literal characters. 例如,字符串 "*t" 搜索以字母 "t" 结尾的所有名称。For example, the string "*t" searches for all names in ending with the letter "t". ".". searchPattern 字符串 "s*" 搜索 path 以字母 "s" 开头的所有名称。The searchPattern string "s*" searches for all names in path beginning with the letter "s".

EnumerateDirectoriesGetDirectories 方法的区别如下:The EnumerateDirectories and GetDirectories methods differ as follows:

因此,在处理多个文件和目录时,EnumerateDirectories 可能更高效。Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

此方法预先填充以下 DirectoryInfo 属性的值:This method pre-populates the values of the following DirectoryInfo properties:

未缓存返回的集合;对集合的 GetEnumerator 方法的每个调用都将开始一个新的枚举。The returned collection is not cached; each call to the GetEnumerator method on the collection will start a new enumeration.

EnumerateDirectories()

返回当前目录中目录信息的可枚举集合。Returns an enumerable collection of directory information in the current directory.

public:
 System::Collections::Generic::IEnumerable<System::IO::DirectoryInfo ^> ^ EnumerateDirectories();
public System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo> EnumerateDirectories ();
member this.EnumerateDirectories : unit -> seq<System.IO.DirectoryInfo>
Public Function EnumerateDirectories () As IEnumerable(Of DirectoryInfo)

返回

当前目录中目录的可枚举集合。An enumerable collection of directories in the current directory.

例外

封装在 DirectoryInfo 对象中的路径无效(例如,在未映射的驱动器上)。The path encapsulated in the DirectoryInfo object is invalid (for example, it is on an unmapped drive).

调用方没有所要求的权限。The caller does not have the required permission.

示例

下面的示例枚举 C:\Program Files 目录下的子目录,并使用 LINQ 查询返回在2009之前创建的所有目录的名称,方法是检查 CreationTimeUtc 属性的值。The following example enumerates the subdirectories under the C:\Program Files directory and uses a LINQ query to return the names of all directories that were created before 2009 by checking the value of the CreationTimeUtc property.

如果只需要子目录的名称,请使用静态 Directory 类以提高性能。If you only need the names of the subdirectories, use the static Directory class for better performance. 有关示例,请参阅 EnumerateDirectories(String) 方法。For an example, see the EnumerateDirectories(String) method.

using System;
using System.IO;

namespace EnumDir
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set a variable to the Documents path.
            string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            DirectoryInfo dirPrograms = new DirectoryInfo(docPath);
            DateTime StartOf2009 = new DateTime(2009, 01, 01);

            var dirs = from dir in dirPrograms.EnumerateDirectories()
            where dir.CreationTimeUtc > StartOf2009
            select new
            {
                ProgDir = dir,
            };

            foreach (var di in dirs)
            {
                Console.WriteLine($"{di.ProgDir.Name}");
            }
        }
    }
}
// </Snippet1>
Imports System.IO

Module Module1

    Sub Main()

        Dim dirPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        Dim dirPrograms As New DirectoryInfo(dirPath)
        Dim StartOf2009 As New DateTime(2009, 1, 1)

        Dim dirs = From dir In dirPrograms.EnumerateDirectories()
                   Where dir.CreationTimeUtc > StartOf2009

        For Each di As DirectoryInfo In dirs
            Console.WriteLine("{0}", di.Name)
        Next

    End Sub

End Module

注解

EnumerateDirectoriesGetDirectories 方法的区别如下:The EnumerateDirectories and GetDirectories methods differ as follows:

因此,在处理多个文件和目录时,EnumerateDirectories 可能更高效。Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

此方法预先填充以下 DirectoryInfo 属性的值:This method pre-populates the values of the following DirectoryInfo properties:

未缓存返回的集合;对集合的 GetEnumerator 方法的每个调用都将开始一个新的枚举。The returned collection is not cached; each call to the GetEnumerator method on the collection will start a new enumeration.

EnumerateDirectories(String)

返回与指定的搜索模式匹配的目录信息的可枚举集合。Returns an enumerable collection of directory information that matches a specified search pattern.

public:
 System::Collections::Generic::IEnumerable<System::IO::DirectoryInfo ^> ^ EnumerateDirectories(System::String ^ searchPattern);
public System.Collections.Generic.IEnumerable<System.IO.DirectoryInfo> EnumerateDirectories (string searchPattern);
member this.EnumerateDirectories : string -> seq<System.IO.DirectoryInfo>
Public Function EnumerateDirectories (searchPattern As String) As IEnumerable(Of DirectoryInfo)

参数

searchPattern
String

要与目录名匹配的搜索字符串。The search string to match against the names of directories. 此参数可以包含有效文本路径和通配符(* 和 ?)的组合,但不支持正则表达式。This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.

返回

searchPattern 匹配的目录的可枚举集合。An enumerable collection of directories that matches searchPattern.

例外

searchPatternnullsearchPattern is null.

封装在 DirectoryInfo 对象中的路径无效(例如,在未映射的驱动器上)。The path encapsulated in the DirectoryInfo object is invalid (for example, it is on an unmapped drive).

调用方没有所要求的权限。The caller does not have the required permission.

注解

searchPattern 可以是文字和通配符的组合,但不支持正则表达式。searchPattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. searchPattern中允许使用以下通配符说明符。The following wildcard specifiers are permitted in searchPattern.

通配符说明符Wildcard specifier 匹配Matches
* (星号)* (asterisk) 此位置中的零个或多个字符。Zero or more characters in that position.
?? (问号)(question mark) 此位置中的零个或一个字符。Zero or one character in that position.

通配符以外的字符为原义字符。Characters other than the wildcard are literal characters. 例如,字符串 "*t" 搜索以字母 "t" 结尾的所有名称。For example, the string "*t" searches for all names in ending with the letter "t". ".". searchPattern 字符串 "s*" 搜索 path 以字母 "s" 开头的所有名称。The searchPattern string "s*" searches for all names in path beginning with the letter "s".

EnumerateDirectoriesGetDirectories 方法的区别如下:The EnumerateDirectories and GetDirectories methods differ as follows:

因此,在处理多个文件和目录时,EnumerateDirectories 可能更高效。Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

此方法预先填充以下 DirectoryInfo 属性的值:This method pre-populates the values of the following DirectoryInfo properties:

未缓存返回的集合;对集合的 GetEnumerator 方法的每个调用都将开始一个新的枚举。The returned collection is not cached; each call to the GetEnumerator method on the collection will start a new enumeration.

适用于