//静态方法
public static bool file()
{
try
{
//指定路径
string name = "指定路径";
//指定类型 *.txt .csv*
string types = "*.txt*";
// 查询当前目录以及目录下的子目录
SearchOption searchOption = SearchOption.AllDirectories;
//查询当前的目录 不包含当前目录下的子目录
// searchOption = SearchOption.TopDirectoryOnly;
// 将读取的文件存放在数组中
string[] Array=Directory.GetFiles(name,types,searchOption);
//存放路径
string[] path=new string[Array.Length];
int i = 0;
//判断文件是否存在
//File.Exists()检测文件是否存在
// 检测文件夹是否存在
if (Directory.Exists(name))
{
//也可使用lambda 指定后缀名
// var lam = Array.Where(e=> e.EndsWith(".txt"));
// 循环文件数组
foreach (string str in Array)
{
FileInfo fi = new FileInfo(str);
// 输出文件名称
Console.WriteLine(fi.Name);
// 将读取到的路径存储到Array数组中
path[i++] = fi.FullName;
}
// 循环路径数组 读取文件内容
foreach (var item in path)
{
//清零重新计算
i = 0;
// 小文件使用File方法,直接读取
Console.WriteLine(File.ReadAllText(path[i++]));
// 文件流处理
//using (StreamReader reader = new StreamReader(path[i++]))
//{
// string line;
// if (reader.ReadLine!=null)
// {
// line = reader.ReadLine();
// }
//}
}
return true;
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine("文件不存在"+ex.Message);
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("无权限");
}
return false;
}