DirectoryInfo.EnumerateDirectories DirectoryInfo.EnumerateDirectories DirectoryInfo.EnumerateDirectories DirectoryInfo.EnumerateDirectories Method

定義

傳回目前目錄中目錄資訊的可列舉集合。Returns an enumerable collection of directory information in the current directory.

多載

EnumerateDirectories(String, SearchOption) EnumerateDirectories(String, SearchOption) EnumerateDirectories(String, SearchOption)

傳回符合指定之搜尋模式和搜尋子目錄選項的目錄資訊的可列舉集合。Returns an enumerable collection of directory information that matches a specified search pattern and search subdirectory option.

EnumerateDirectories(String, EnumerationOptions) EnumerateDirectories(String, EnumerationOptions) EnumerateDirectories(String, EnumerationOptions)
EnumerateDirectories() EnumerateDirectories() EnumerateDirectories() EnumerateDirectories()

傳回目前目錄中目錄資訊的可列舉集合。Returns an enumerable collection of directory information in the current directory.

EnumerateDirectories(String) EnumerateDirectories(String) EnumerateDirectories(String) EnumerateDirectories(String)

傳回符合指定之搜尋模式的目錄資訊的可列舉集合。Returns an enumerable collection of directory information that matches a specified search pattern.

EnumerateDirectories(String, SearchOption) EnumerateDirectories(String, SearchOption) 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>

參數

searchPattern
String String String 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 SearchOption 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.

例外狀況

封裝在 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". ".". 字串 "s*" 會path搜尋開頭為字母 "s" 的所有名稱。 searchPatternThe 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) EnumerateDirectories(String, EnumerationOptions) EnumerateDirectories(String, EnumerationOptions)

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>

參數

searchPattern
String String String String

傳回

EnumerateDirectories() EnumerateDirectories() EnumerateDirectories() 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 查詢,藉由檢查CreationTimeUtc屬性的值,傳回2009之前建立的所有目錄名稱。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) EnumerateDirectories(String) EnumerateDirectories(String) 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 String String 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.

例外狀況

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". ".". 字串 "s*" 會path搜尋開頭為字母 "s" 的所有名稱。 searchPatternThe 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.

適用於