System.IO.Directory.EnumerateFiles 方法 (String)
方法描述
返回指定路径中的文件名的可枚举集合。
语法定义(C# System.IO.Directory.EnumerateFiles 方法 (String) 的用法)
public static IEnumerableEnumerateFiles( string path )
参数/返回值
| 参数值/返回值 | 参数类型/返回类型 | 参数描述/返回描述 |
|---|---|---|
| path | System-String | 要搜索的目录。 |
| 返回值 | System.Collections.Generic.IEnumerable |
由 path 指定的目录中的文件名称的可枚举集合。 |
提示和注释
可以使用 path 参数指定相对路径信息。 相对路径信息被解释为相对于您可以使用 GetCurrentDirectory 方法来确定的当前工作目录。
EnumerateFiles 和 GetFiles 方法不同点在于:当使用 EnumerateFiles 时,您可以在返回整个集合之前开始枚举名称集合;当您使用 GetFiles 时,则必须等待整个名称数组都被返回后才能访问数组。 因此,在处理许多文件和目录时,EnumerateFiles 可能更高效。
不缓存返回的集合;每次在集合上调用 GetEnumerator 都将启动一个新枚举。
System.IO.Directory.EnumerateFiles 方法 (String)例子
下面的示例枚举指定目录中的文件,读取文件的每一行,然后显示包含字符串“Europe”的行。
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
class Program
{
static void Main(string[] args)
{
try
{
// LINQ query for all files containing the word 'Europe'.
var files = from file in
Directory.EnumerateFiles(@"\\archives1\library\")
where file.ToLower().Contains("europe")
select file;
// Show results.
foreach (var file in files)
{
Console.WriteLine("{0}", file);
}
Console.WriteLine("{0} files found.",
files.Count().ToString());
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
}
}
异常
| 异常 | 异常描述 |
|---|---|
| ArgumentException | path 是零长度字符串、只包含空白或者包含在 GetInvalidPathChars 定义的无效字符。 |
| ArgumentNullException | path 为 null。 |
| DirectoryNotFoundException | path 无效,比如引用未映射的驱动器。 |
| IOException | path 是一个文件名。 |
| PathTooLongException | 指定的路径、文件名或者两者都超出了系统定义的最大长度。 例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。 |
| SecurityException | 调用方没有所要求的权限。 |
| UnauthorizedAccessException | 调用方没有所要求的权限。 |
版本信息
.NET Framework 受以下版本支持:4 .NET Framework Client Profile 受以下版本支持:4
适用平台
Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。