Directory.GetFiles 方法

定义

返回满足指定条件的文件的名称。

重载

GetFiles(String)

返回指定目录中文件的名称(包括其路径)。

GetFiles(String, String)

返回指定目录中与指定的搜索模式匹配的文件的名称(包含其路径)。

GetFiles(String, String, EnumerationOptions)

返回指定目录中与指定的搜索模式和枚举选项匹配的文件的名称(包括其路径)。

GetFiles(String, String, SearchOption)

返回指定目录中与指定的搜索模式匹配的文件的名称(包含其路径),使用某个值确定是否要搜索子目录。

GetFiles(String)

Source:
Directory.cs
Source:
Directory.cs
Source:
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 和 .NET Core 版本早于 2.1: 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)

Source:
Directory.cs
Source:
Directory.cs
Source:
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 和 .NET Core 版本早于 2.1: 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)

Source:
Directory.cs
Source:
Directory.cs
Source:
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 。 字符串 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, SearchOption)

Source:
Directory.cs
Source:
Directory.cs
Source:
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 。 字符串 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 任务

另请参阅

适用于