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

方法描述

获取指定目录中的子目录的名称(包括其路径)。

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

public static string[] GetDirectories(
	string path
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
path System-String 为其返回子目录名称的数组的路径。
返回值 System.String[] path 中子目录名称的数组。

提示和注释

如果不存在子目录,该方法将返回空数组。

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

此方法与将星号 (*) 指定为搜索模式的 GetDirectories 方法相同。

由此方法返回的名称以 path 中提供的目录信息为前缀。

path 参数不区分大小写。

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

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

下面的代码示例接受命令行上的一组文件名或目录名,确定名称类型,然后相应地进行处理。

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

异常

异常 异常描述
UnauthorizedAccessException 调用方没有所要求的权限。
ArgumentException path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。
ArgumentNullException path 为 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 系统要求。