System.IO.DirectoryInfo.GetFiles 方法 (String)

方法描述

返回当前目录中与给定的搜索模式匹配的文件列表。

语法定义(C# System.IO.DirectoryInfo.GetFiles 方法 (String) 的用法)

public FileInfo[] GetFiles(
	string searchPattern
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
searchPattern System-String 搜索字符串(如“*.txt”)。
返回值 System.IO.FileInfo[] FileInfo 类型的数组。

提示和注释

如果 DirectoryInfo 中没有文件,则此方法返回一个空数组。

在 searchPattern 参数中允许使用以下通配说明符。

通配符

说明

*

零个或多个字符。

?

正好一个字符。

返回文件的名称顺序无法保证;如果需要特定排序顺序,请使用 Sort() 方法。

允许使用通配符。 例如,searchPattern 字符串“*.txt”搜索扩展名为“txt”的所有文件名称。 searchPattern 字符串“s*”会搜索所有以字母“s”开头的文件名。 如果 DirectoryInfo 中没有文件或没有与 searchPattern 字符串匹配的文件,则此方法返回一个空数组。

注意

在 searchPattern 中使用星号通配符时(例如,“*.txt”),匹配行为会根据指定文件扩展名的长度而有所不同。 文件扩展名正好是三个字符的 searchPattern 将返回扩展名为三个或更多字符的文件,其中前三个字符与 searchPattern 中指定的文件扩展名匹配。 文件扩展名为一个、两个或三个以上字符的 searchPattern 仅返回扩展名长度正好与 searchPattern 中指定的文件扩展名匹配的文件。 使用问号通配符字符时,此方法仅返回与指定文件扩展名匹配的文件。 例如,假设目录下有两个文件“file1.txt”和“file1.txtother”,使用“file?.txt”搜索模式时只返回第一个文件,而使用“file*.txt”搜索模式时会同时返回这两个文件。

以下列表显示了 searchPattern 参数的不同长度的行为:

“*.abc”返回扩展名为 .abc、.abcd、.abcde、.abcdef 等的文件。

“*.abcd”只返回扩展名为 .abcd 的文件。

“*.abcde”只返回扩展名为 .abcde 的文件。

“*.abcdef”只返回扩展名为 .abcdef 的文件。

注意

因为此方法仅检查同时具有 8.3 文件名格式和长文件名格式的文件,类似“*1*.txt”的搜索模式可能会返回意外的文件名。 例如,使用“*1*.txt”的搜索模式将返回“longfilename.txt”,因为等效的 8.3 文件名格式为“longf~1.txt”。

此方法预填充下面的 FileInfo 属性的值:

Attributes

CreationTime

CreationTimeUtc

LastAccessTime

LastAccessTimeUtc

LastWriteTime

LastWriteTimeUtc

Length

System.IO.DirectoryInfo.GetFiles 方法 (String)例子

下面的示例对包含指定字母的目录及文件进行计数。

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            DirectoryInfo di = new DirectoryInfo(@"c:\");

            // Get only subdirectories that contain the letter "p."
            DirectoryInfo[] dirs = di.GetDirectories("*p*");

            Console.WriteLine("Number of directories with a p: {0}", dirs.Length);

            // Count all the files in each subdirectory that contain the letter "e."
            foreach (DirectoryInfo diNext in dirs) 
            {
                Console.WriteLine("The number of files in {0} with an e is {1}", diNext, 
                    diNext.GetFiles("*e*").Length);
            }
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

异常

异常 异常描述
ArgumentException searchPattern 包含由 GetInvalidPathChars 方法定义的一个或多个无效字符。
ArgumentNullException searchPattern 为 null。
DirectoryNotFoundException 路径无效(例如,在未映射的驱动器上)。
SecurityException 调用方没有所要求的权限。

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。