现在的位置: 首页 > 综合 > 正文

Directory.EnumerateFiles的使用

2013年09月21日 ⁄ 综合 ⁄ 共 1786字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.