
在我读取数据时需要读取路径下所有的excel文件,所以用到了这个记录一下
Directory.GetFiles方法命名空间:System.IO
重载
GetFiles(String path)
参数:path:目录的相对路径或绝对路径
返回值:返回指定目录中文件的名称(包括其路径)。
GetFiles(String path, String searchPattern)
参数:path:目录的相对路径或绝对路径
searchPattern:与path中的文件名匹配的搜索字符串。 此参数可以包含有效文本路径和通配符(* 和 ?)的组合,不 支持正则表达式
返回值:返回指定目录中与指定的搜索模式匹配的文件的名称(包含其路径)。
GetFiles(String path, String searchPattern, EnumerationOptions enumerationOptions)
参数:path:目录的相对路径或绝对路径
searchPattern:与path中的文件名匹配的搜索字符串。 此参数可以包含有效文本路径和 通配符(* 和 ?)的组合,不支持正则表达式
EnumerationOptions: 描述要使用的搜索和枚举配置的对象。
返回值:返回指定目录中与指定的搜索模式和枚举选项匹配的文件的名称(包括其路径)。
GetFiles(String path, String searchPattern, SearchOption searchOption)
参数:path:目录的相对路径或绝对路径
searchPattern:与path中的文件名匹配的搜索字符串。 此参数可以包含有效文本路径和 通配符(* 和 ?)的组合,不支持正则表达式
SearchOption: 用于指定搜索操作是应包含所有子目录还是仅包含当前目录的枚举值之一。
返回值:返回指定目录中与指定的搜索模式匹配的文件的名称(包含其路径)。
例子:
public static void ReadAllExcel()
{
string str = System.Environment.CurrentDirectory;
string [] filePath = Directory.GetFiles(str, "*.xls", SearchOption.AllDirectories);
foreach(string path in filePath)
{
do some things;
}
}
Directory.EnumerateFiles 方法
命名空间:System.IO
重载
EnumerateFiles(String path)
参数:path:目录的相对路径或绝对路径
返回值:一个可枚举集合,它包含 path 指定的目录中与指定的搜索模式和搜索选项匹配的文件的完整名称(包括路径)。
EnumerateFiles(String path, String)
参数:path:目录的相对路径或绝对路径
searchPattern:与path中的文件名匹配的搜索字符串。 此参数可以包含有效文本路径和 通配符(* 和 ?)的组合,不支持正则表达式
返回值:一个可枚举集合,它包含 path 指定的目录中与指定的搜索模式和搜索选项匹配的文件的完整名称(包括路径)。
EnumerateFiles(String path, String searchPattern, EnumerationOptions enumerationOptions)
参数:path:目录的相对路径或绝对路径
searchPattern:与path中的文件名匹配的搜索字符串。 此参数可以包含有效文本路径和 通配符(* 和 ?)的组合,不支持正则表达式
EnumerationOptions: 描述要使用的搜索和枚举配置的对象。
返回值:返回一个可枚举集合,它包含 path 指定的目录中与指定的搜索模式和枚举选项匹配的文件的完整名称(包括路径)。
EnumerateFiles(String path, String searchPattern, SearchOption searchOption)
参数:path:目录的相对路径或绝对路径
searchPattern:与path中的文件名匹配的搜索字符串。 此参数可以包含有效文本路径和 通配符(* 和 ?)的组合,不支持正则表达式
SearchOption: 指定搜索操作是应仅包含当前目录还是应包含所有子目录的枚举值之一。 默认值是 TopDirectoryOnly。
返回值:一个可枚举集合,它包含 path 指定的目录中与指定的搜索模式和搜索选项匹配的文件的完整名称(包括路径)。
例子:
using System;
using System.Linq;
using System.IO;
class Program
{
static void Main(string[] args)
{
try
{
// LINQ query for all .txt files containing the word 'Europe'.
var files = from file in Directory.EnumerateFiles(@"\archives1library", "*.txt")
where file.ToLower().Contains("europe")
select file;
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);
}
}
}
两者区别
使用时 EnumerateFiles ,可以在返回整个集合之前开始枚举名称的集合; 使用时 GetFiles ,必须等待返回整个名称数组,然后才能访问数组。 因此,在处理多个文件和目录时, EnumerateFiles 可能更高效。
再加个获取当前程序工作目录的方法
Directory.GetCurrentDirectory 方法命名空间:System.IO
Directory.GetCurrentDirectory()
返回值:一个字符串,该字符串包含当前工作目录的绝对路径且不以反斜杠 () 结尾。