C#遍历目录和文件(使用Linq)

 

语言越来越强大,程序员越来越轻松。
1.枚举所有目录中的名称

 

try
            {
                
//返回指定路径中与搜索模式匹配的文件名称的可枚举集合,还可以搜索子目录。
                var files = from file in Directory.EnumerateFiles(@"F:/电影/""*.txt", SearchOption.AllDirectories)
                            
from line in File.ReadLines(file)
                            
where line.Contains("Microsoft")
                            
select new
                            {
                                File
=file,
                                Line
=line
                            };
                
foreach (var f in files)
                {
                    Console.WriteLine(
"{0}/t{1}", f.File, f.Line);
                }
                Console.WriteLine(files.Count().ToString());
            }

            
catch (UnauthorizedAccessException UAEx)
            {
                Console.WriteLine(UAEx.Message);
            }
            
catch(PathTooLongException PathEx)
            {
                Console.WriteLine(PathEx.Message);
            }

2.枚举当前目录的目录及其文件

 

  DirectoryInfo Dir = new DirectoryInfo(@"F:/电影");
            
var files = from file
                            
in Dir.EnumerateFiles()
                            
select file;

            
foreach (var f in files)
            {
                Console.WriteLine(
"filename:{0}",f);
            }

            
var directory = from dir
                            
in Dir.EnumerateDirectories()
                            
select dir;
            
foreach (var f in directory)
            {
                Console.WriteLine(
"DirectotyName:{0}", f);
            }

url:http://greatverve.cnblogs.com/archive/2011/07/04/linq-dir-file.html#
posted @ 2011-07-04 08:56  大气象  阅读(2431)  评论(4编辑  收藏  举报
http://www.tianqiweiqi.com