System.IO.Directory.GetDirectories 方法 (String, String)

方法描述

在当前目录获取与指定搜索模式匹配的目录的数组(包括它们的路径)。

语法定义(C# System.IO.Directory.GetDirectories 方法 (String, String) 的用法)

public static string[] GetDirectories(
	string path,
	string searchPattern
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
path System-String 要搜索的路径。
searchPattern System-String 要与 path 中的文件名匹配的搜索字符串。此参数不能以两个句点(“..”)结束,不能在 DirectorySeparatorChar 或 AltDirectorySeparatorChar 的前面包含两个句点(“..”),也不能包含 InvalidPathChars 中的任何字符。
返回值 System.String[] 与搜索模式匹配的目录的 String 数组。

提示和注释

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

通配符

说明

*

零个或多个字符。

?

正好一个字符。

通配说明符以外的字符表示它们自己。 例如,searchPattern 字符串“*t”搜索 path 中所有以字母“t”结尾的名称。 searchPattern 字符串“s*”搜索 path 中所有以字母“s”开头的名称。

如果不存在子目录,或不存在与 searchPattern 参数匹配的子目录,此方法将返回一个空数组。

允许 path 参数指定相对或绝对路径信息。 相对路径信息被解释为相对于当前工作目录。 若要获取当前工作目录,请参见 GetCurrentDirectory。

path 参数不区分大小写。

有关通用 I/O 任务的列表,请参见通用 I/O 任务。

System.IO.Directory.GetDirectories 方法 (String, String)例子

下面的代码示例计算以指定的字母开头的路径中的目录数。

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // Only get subdirectories that begin with the letter "p."
            string[] dirs = Directory.GetDirectories(@"c:\", "p*");
            Console.WriteLine("The number of directories starting with p is {0}.", dirs.Length);
            foreach (string dir in dirs) 
            {
                Console.WriteLine(dir);
            }
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

异常

异常 异常描述
UnauthorizedAccessException 调用方没有所要求的权限。
ArgumentException
  • path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。
  • searchPattern 不包含有效模式。
ArgumentNullException path 或 searchPattern 为 null。
PathTooLongException 指定的路径、文件名或者两者都超出了系统定义的最大长度。 例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。
IOException path 是一个文件名。
DirectoryNotFoundException 指定的路径无效(例如,它位于未映射的驱动器上)。

命名空间

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 系统要求。