Directory.EnumerateFiles的使用

Directory.EnumerateFiles的使用
2010年11月14日 云飞扬
-
?[Copy to clipboard]View Code CSHARPusing 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<string>().ToString());
  }
  catch (UnauthorizedAccessException UAEx)
  {
   Console.WriteLine(UAEx.Message);
  }
  catch (PathTooLongException PathEx)
  {
   Console.WriteLine(PathEx.Message);
        }
 }
}
 
 
Phil Haack has an interesting post about this topic, where he presents the following solution:
 
public static bool IsNullOrEmpty<T>(this IEnumerable<T> items) {
    return items == null || !items.Any();
}This solution, unfortunately, suffers from a common problem related to handling IEnumerables. The assumption that you can iterate over enumerable more than once. This hold true for things like collections, but in many cases, this sort of code will silently hide data:
 
var files = Directory.EnumerateFiles(".","*.cs");
if(files.IsNullOrEmpty())
{
    Cosnole.WriteLine("No files");
}
else
{
   foreach(var file in files)
   {
          Console.WriteLine(file);
   }
}The first file will never appear here.
 
A better solution is:
 
public static bool IsNullOrEmpty<T>(this IEnumerable<T> items, out IEnumerable<T> newItems)
{
    newItems = items;
    if(items == null)
        return false;
 
    var enumerator = items.GetEnumerator();
    if(enumerator.MoveNext() == false)
        return false;
 
    newItems = new[]{enumerator.Current}.Concat(enumerator);
 
    return true;
}That will not lose data.

原创文章转载请注明出处:云飞扬IT的blog


本文来自: 本站内容欢迎转载,但是禁止去掉本文链接(转载无妨,去掉链接可耻!):http://www.ajaxcn.net/archives/1519

阅读更多
个人分类: c#
想对作者说点什么? 我来说一句

使用使用使用

2013年02月26日 48KB 下载

没有更多推荐了,返回首页

不良信息举报

Directory.EnumerateFiles的使用

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭