Directory.GetFiles 方法

定義

傳回符合指定準則之檔案的名稱。

多載

GetFiles(String)

傳回指定目錄中的檔案名稱 (包括路徑)。

GetFiles(String, String)

傳回指定目錄中符合指定搜尋模式的檔案名稱 (包括檔案的路徑)。

GetFiles(String, String, EnumerationOptions)

傳回所指定目錄中符合所指定搜尋模式與列舉選項的檔案名稱 (包含其路徑)。

GetFiles(String, String, SearchOption)

傳回指定目錄中符合指定搜尋模式的檔案名稱 (包括檔案的路徑),並使用值判斷是否搜尋子目錄。

GetFiles(String)

來源:
Directory.cs
來源:
Directory.cs
來源:
Directory.cs

傳回指定目錄中的檔案名稱 (包括路徑)。

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

參數

path
String

要搜尋之目錄的相對或絕對路徑。 這個字串不會區分大小寫。

傳回

String[]

指定之目錄中的檔案完整名稱 (包括路徑) 陣列,如果找不到任何檔案則為空陣列。

例外狀況

path 為檔案名稱。

-或-

發生網路錯誤。

呼叫端沒有必要的權限。

.NET Framework和 2.1 之前的 .NET Core 版本: path 是長度為零的字串、只包含空白字元,或包含一或多個無效字元。 您可以使用 GetInvalidPathChars() 方法查詢無效字元。

pathnull

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

指定的路徑未找到或無效 (例如,它位於未對應的磁碟機上)。

範例

下列範例示範如何使用 GetFiles 方法,從使用者指定的位置傳回檔案名。 此範例設定為攔截這個方法通用的所有錯誤。

// 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);	
    }
}
module RecursiveFileProcessor

open System.IO

// Insert logic for processing found files here.
let processFile path =
    printfn $"Processed file '%s{path}'."

// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
let rec processDirectory targetDirectory =
    // Process the list of files found in the directory.
    let fileEntries = Directory.GetFiles targetDirectory
    for fileName in fileEntries do
        processFile fileName

    // Recurse into subdirectories of this directory.
    let subdirectoryEntries = Directory.GetDirectories targetDirectory
    for subdirectory in subdirectoryEntries do
        processDirectory subdirectory

[<EntryPoint>]
let main args =
    for path in args do
        if File.Exists path then
            // This path is a file
            processFile path
        elif Directory.Exists path then
            // This path is a directory
            processDirectory path
        else
            printfn $"{path} is not a valid file or directory."
    0
' 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

備註

EnumerateFilesGetFiles 方法不同,如下所示:當您使用 EnumerateFiles 時,可以在傳回整個集合之前開始列舉名稱的集合;當您使用 GetFiles 時,必須先等候傳回整個名稱陣列,才能存取陣列。 因此,當您使用許多檔案和目錄時, EnumerateFiles 可能會更有效率。

傳回的檔案名會附加至提供的 path 參數。

這個方法與指定為搜尋模式的星號 (*) 相同 GetFiles(String, String)

參數 path 可以指定相對或絕對路徑資訊。 相對路徑資訊會解譯為相對於目前工作目錄。 若要取得目前的工作目錄,請參閱 GetCurrentDirectory

不保證傳回檔案名的順序;如果需要特定排序次序,請使用 Sort 方法。

參數的 path 區分大小寫會對應至程式碼執行所在的檔案系統。 例如,在 NTFS 上不區分大小寫 (預設 Windows 檔案系統) 和 Linux 檔案系統上區分大小寫。

如需一般 I/O 工作的清單,請參閱 一般 I/O 工作

另請參閱

適用於

GetFiles(String, String)

來源:
Directory.cs
來源:
Directory.cs
來源:
Directory.cs

傳回指定目錄中符合指定搜尋模式的檔案名稱 (包括檔案的路徑)。

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

參數

path
String

要搜尋之目錄的相對或絕對路徑。 這個字串不會區分大小寫。

searchPattern
String

要比對 path 中檔案名稱的搜尋字串。 這個參數可以包含有效常值路徑與萬用 (* 和 ?) 字元的組合,但是不支援規則運算式。

傳回

String[]

指定目錄中,符合指定搜尋模式的檔案完整名稱 (包括路徑) 陣列,如果找不到任何檔案則為空陣列。

例外狀況

path 為檔案名稱。

-或-

發生網路錯誤。

呼叫端沒有必要的權限。

.NET Framework和 2.1 之前的 .NET Core 版本: path 是長度為零的字串、只包含空白字元,或包含一或多個無效字元。 您可以使用 GetInvalidPathChars() 查詢無效字元。

-或-

searchPattern 不包含有效模式。

pathsearchPatternnull

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

指定的路徑未找到或無效 (例如,它位於未對應的磁碟機上)。

範例

下列範例會計算以指定字母開頭的檔案數目。

using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      
      // Only get files that begin with the letter "c".
      array<String^>^dirs = Directory::GetFiles( "c:\\", "c*" );
      Console::WriteLine( "The number of files starting with c 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 files that begin with the letter "c".
            string[] dirs = Directory.GetFiles(@"c:\", "c*");
            Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
            foreach (string dir in dirs)
            {
                Console.WriteLine(dir);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
open System.IO

try
    // Only get files that begin with the letter "c".
    let dirs = Directory.GetFiles(@"c:\", "c*")
    printfn $"The number of files starting with c is {dirs.Length}."
    for dir in dirs do
        printfn $"{dir}"
with e ->
    printfn $"The process failed: {e}"
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        Try
            ' Only get files that begin with the letter "c".
            Dim dirs As String() = Directory.GetFiles("c:\", "c*")
            Console.WriteLine("The number of files starting with c 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

備註

傳回的檔案名會附加至提供的 path 參數,而且不保證傳回的檔案名的順序;如果需要特定排序次序, Sort 請使用 方法。

searchPattern 可以是常值和萬用字元的組合,但不支援正則運算式。 在 中 searchPattern 允許下列萬用字元規範。

萬用字元規範 相符項
* (星號) 該位置中的零或多個字元。
? (問號) 該位置中只有一個字元。

萬用字元以外的字元是常值字元。 例如, searchPattern 字串 「*t」 會搜尋以字母 「t」 結尾的所有名稱 path 。 字串 searchPattern 「s*」 會搜尋以字母 「s」 開頭的所有名稱 path

searchPattern 不能以兩個句號結尾 (」。」) 或包含兩個 (句點」。」) 後面 DirectorySeparatorChar 接著 或 AltDirectorySeparatorChar ,也無法包含任何無效字元。 您可以使用 GetInvalidPathChars 方法查詢無效字元。

注意

僅.NET Framework:當您在 searchPattern 中使用星號萬用字元,並指定三個字元副檔名時,例如 「*.txt」,此方法也會傳回副檔名開頭為指定副檔名的檔案。 例如,搜尋模式 「*.xls」 會同時傳回 「book.xls」 和 「book.xlsx」。 只有在搜尋模式中使用星號,且提供的副檔名剛好是三個字元時,才會發生此行為。 如果您在搜尋模式的某處使用問號萬用字元,此方法只會傳回完全符合指定副檔名的檔案。 下表描述.NET Framework中的這個異常狀況。

目錄中的檔案 搜尋模式 .NET 5+ 傳回 .NET Framework傳回
file.ai file.aif *。艾 file.ai file.ai
book.xls,book.xlsx *.xls book.xls book.xls,book.xlsx
ello.txt、hello.txt、hello.txtt ?ello.txt ello.txt,hello.txt ello.txt,hello.txt

注意

因為此方法會檢查檔案名格式為 8.3 和長檔名格式的檔案名,所以類似 「*1*.txt」 的搜尋模式可能會傳回非預期的檔案名。 例如,使用 「*1*.txt」 的搜尋模式會傳回 「longfilename.txt」,因為對等的 8.3 檔案名格式為 「LONGFI~1.TXT」。

EnumerateFilesGetFiles 方法不同,如下所示:當您使用 EnumerateFiles 時,可以在傳回整個集合之前開始列舉名稱的集合;當您使用 GetFiles 時,必須先等候傳回整個名稱陣列,才能存取陣列。 因此,當您使用許多檔案和目錄時, EnumerateFiles 可能會更有效率。

參數 path 可以指定相對或絕對路徑資訊。 相對路徑資訊會解譯為相對於目前工作目錄。 若要取得目前的工作目錄,請參閱 GetCurrentDirectory

參數的 path 區分大小寫會對應至執行程式碼的檔案系統。 例如,在 NTFS 上不區分大小寫 (預設 Windows 檔案系統) 和 Linux 檔案系統上區分大小寫。

如需一般 I/O 工作的清單,請參閱 一般 I/O 工作

另請參閱

適用於

GetFiles(String, String, EnumerationOptions)

來源:
Directory.cs
來源:
Directory.cs
來源:
Directory.cs

傳回所指定目錄中符合所指定搜尋模式與列舉選項的檔案名稱 (包含其路徑)。

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

參數

path
String

要搜尋之目錄的相對或絕對路徑。 這個字串不會區分大小寫。

searchPattern
String

要比對 path 中子目錄名稱的搜尋字串。 這個參數可以包含有效常值與萬用字元的組合,但是不支援規則運算式。

enumerationOptions
EnumerationOptions

物件,描述要使用的搜尋和列舉組態。

傳回

String[]

在所指定目錄中,符合所指定搜尋模式與列舉選項之檔案完整名稱 (包含路徑) 的陣列,如果找不到任何檔案則為空陣列。

例外狀況

path 為檔案名稱。

-或-

發生網路錯誤。

呼叫端沒有必要的權限。

.NET Framework和 2.1 之前的 .NET Core 版本: path 是長度為零的字串、只包含空白字元,或包含一或多個無效字元。 您可以使用 GetInvalidPathChars() 查詢無效字元。

-或-

searchPattern 不包含有效模式。

pathsearchPatternnull

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

指定的路徑未找到或無效 (例如,它位於未對應的磁碟機上)。

備註

傳回的檔案名會附加至提供的 path 參數,而且不保證傳回的檔案名順序;如果需要特定排序次序, Sort 請使用 方法。

searchPattern 可以是常值和萬用字元的組合,但不支援正則運算式。 在 中 searchPattern 允許下列萬用字元規範。

萬用字元規範 相符項
* (星號) 該位置中的零或多個字元。
? (問號) 該位置中只有一個字元。

萬用字元以外的字元是常值字元。 例如, searchPattern 字串 「*t」 會搜尋以字母 「t」 結尾的所有名稱 path 。 字串 「s*」 會 searchPattern 以字母 「s」 開頭搜尋所有名稱 path

searchPattern 不能以兩個句點結尾 (「。」) 或包含兩個句點 (「.」。) 後面接著 DirectorySeparatorCharAltDirectorySeparatorChar ,也無法包含任何不正確字元。 您可以使用 GetInvalidPathChars 方法查詢無效字元。

注意

僅.NET Framework:當您在 中使用 searchPattern 星號萬用字元,並指定三個字元副檔名時,例如 「*.txt」,此方法也會傳回副檔名開頭為指定副檔名的檔案。 例如,搜尋模式 「*.xls」 會同時傳回 「book.xls」 和 「book.xlsx」。 只有在搜尋模式中使用星號,而提供的副檔名只是三個字元時,才會發生此行為。 如果您使用搜尋模式中某處的問號萬用字元,這個方法只會傳回完全符合指定副檔名的檔案。 下表描述.NET Framework中的此異常狀況。

目錄中的檔案 搜尋模式 .NET 5+ 傳回 .NET Framework傳回
file.ai file.aif *。艾 file.ai file.ai
book.xls,book.xlsx *.xls book.xls book.xls,book.xlsx
ello.txt、hello.txt、hello.txtt ?ello.txt ello.txt,hello.txt ello.txt,hello.txt

注意

因為這個方法會檢查具有 8.3 檔案名格式和長檔名格式的檔案名,所以類似 「*1*.txt」 的搜尋模式可能會傳回非預期的檔案名。 例如,使用 「*1*.txt」 的搜尋模式會傳回 「longfilename.txt」,因為對等的 8.3 檔案名格式為 「LONGFI~1.TXT」。

EnumerateFilesGetFiles 方法會如下所示:當您使用 EnumerateFiles 時,可以在傳回整個集合之前開始列舉名稱集合;當您使用 GetFiles 時,必須先等候傳回整個名稱陣列,才能存取陣列。 因此,當您使用許多檔案和目錄時, EnumerateFiles 可能會更有效率。

參數 path 可以指定相對或絕對路徑資訊。 相對路徑資訊會解譯為相對於目前的工作目錄。 若要取得目前的工作目錄,請參閱 GetCurrentDirectory

參數的 path 區分大小寫會對應至執行程式碼的檔案系統。 例如,在 NTFS 上不區分大小寫 (預設 Windows 檔案系統) 和 Linux 檔案系統上區分大小寫。

如需一般 I/O 工作的清單,請參閱 一般 I/O 工作

適用於

GetFiles(String, String, SearchOption)

來源:
Directory.cs
來源:
Directory.cs
來源:
Directory.cs

傳回指定目錄中符合指定搜尋模式的檔案名稱 (包括檔案的路徑),並使用值判斷是否搜尋子目錄。

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

參數

path
String

要搜尋之目錄的相對或絕對路徑。 這個字串不會區分大小寫。

searchPattern
String

要比對 path 中檔案名稱的搜尋字串。 這個參數可以包含有效常值路徑與萬用 (* 和 ?) 字元的組合,但是不支援規則運算式。

searchOption
SearchOption

其中一個列舉值,這個值會指定搜尋作業應該包含所有子目錄或只包含目前目錄。

傳回

String[]

指定目錄中,符合指定搜尋模式和選項的檔案完整名稱 (包括路徑) 陣列,如果找不到任何檔案則為空陣列。

例外狀況

.NET Framework和 2.1 之前的 .NET Core 版本: path 是長度為零的字串、只包含空白字元,或包含一或多個無效字元。 您可以使用 GetInvalidPathChars() 方法查詢無效字元。

-或-

searchPattern 不包含有效模式。

pathsearchpatternnull

searchOption 不是有效的 SearchOption 值。

呼叫端沒有必要的權限。

指定的路徑未找到或無效 (例如,它位於未對應的磁碟機上)。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

path 為檔案名稱。

-或-

發生網路錯誤。

備註

傳回的檔案名會附加至提供的 參數 path ,而且不保證傳回的檔案名順序;如果需要特定排序次序, Sort 請使用 方法。

searchPattern 可以是常值和萬用字元的組合,但不支援正則運算式。 在 中 searchPattern 允許下列萬用字元規範。

萬用字元規範 相符項
* (星號) 該位置中的零或多個字元。
? (問號) 該位置中只有一個字元。

萬用字元以外的字元是常值字元。 例如, searchPattern 字串 「*t」 會搜尋以字母 「t」 結尾的所有名稱 path 。 字串 「s*」 會 searchPattern 以字母 「s」 開頭搜尋所有名稱 path

searchPattern 不能以兩個句點結尾 (「。」) 或包含兩個句點 (「.」。) 後面接著 DirectorySeparatorCharAltDirectorySeparatorChar ,也無法包含任何不正確字元。 您可以使用 GetInvalidPathChars 方法查詢無效字元。

注意

僅.NET Framework:當您在 中使用 searchPattern 星號萬用字元,並指定三個字元副檔名時,例如 「*.txt」,此方法也會傳回副檔名開頭為指定副檔名的檔案。 例如,搜尋模式 「*.xls」 會同時傳回 「book.xls」 和 「book.xlsx」。 只有在搜尋模式中使用星號,而提供的副檔名只是三個字元時,才會發生此行為。 如果您使用搜尋模式中某處的問號萬用字元,這個方法只會傳回完全符合指定副檔名的檔案。 下表描述.NET Framework中的此異常狀況。

目錄中的檔案 搜尋模式 .NET 5+ 傳回 .NET Framework傳回
file.ai file.aif *。艾 file.ai file.ai
book.xls,book.xlsx *.xls book.xls book.xls,book.xlsx
ello.txt、hello.txt、hello.txtt ?ello.txt ello.txt,hello.txt ello.txt,hello.txt

注意

因為這個方法會檢查具有 8.3 檔案名格式和長檔名格式的檔案名,所以類似 「*1*.txt」 的搜尋模式可能會傳回非預期的檔案名。 例如,使用 「*1*.txt」 的搜尋模式會傳回 「longfilename.txt」,因為對等的 8.3 檔案名格式為 「LONGFI~1.TXT」。

EnumerateFilesGetFiles 方法會如下所示:當您使用 EnumerateFiles 時,可以在傳回整個集合之前開始列舉名稱集合;當您使用 GetFiles 時,必須先等候傳回整個名稱陣列,才能存取陣列。 因此,當您使用許多檔案和目錄時, EnumerateFiles 可能會更有效率。

檔案名包含完整路徑。

參數 path 可以指定相對或絕對路徑資訊。 相對路徑資訊會解譯為相對於目前的工作目錄。 若要取得目前的工作目錄,請參閱 GetCurrentDirectory

參數的 path 區分大小寫會對應至執行程式碼的檔案系統。 例如,在 NTFS 上不區分大小寫 (預設 Windows 檔案系統) 和 Linux 檔案系統上區分大小寫。

如需一般 I/O 工作的清單,請參閱 一般 I/O 工作

另請參閱

適用於