c# - 从FileInfo数组中过滤.zip文件

时间:2012-02-22 10:35:26

标签: c# visual-studio-2010 file fileinfo

我有一个FileInfo数组,它返回15个文件和一个“.zip”文件夹。我基本上需要尝试以某种方式从阵列中过滤掉这个“.zip”文件。任何帮助将不胜感激,但似乎我只是撞在砖墙上!这是我试图将其加入的代码;

public List<FileInfo> getInfo(bool recursive, int ageDays)
{
  //Declarations
  DirectoryInfo di = new DirectoryInfo(CurrentFilePath);
  FileInfo[] fi = new FileInfo[0];
  List<FileInfo> results = new List<FileInfo>();
  fileResults = new List<Files>();
  DateTime ageInDays = DateTime.Now.AddDays(-ageDays);

  //Checks for recursive search
  if (recursive)
  {
    try
    {
      fi = di.GetFiles("*.*", SearchOption.AllDirectories);
    }
    catch (Exception)
    {
    }
  }
  else
  {
    try
    {
      fi = di.GetFiles();
    }
    catch (Exception)
    {
    }
  }

  for (int i = 0; i < fi.Length; i++)
  {
    if (fi[i].LastWriteTime < ageInDays)
    {
      results.Add(fi[i]);
    }
  }
  return results;
}

提前致谢!

4 个答案:

答案 0 :(得分:1)

最好更改代码:

for (int i = 0; i < fi.Length; i++)
{
    if ((fi[i].LastWriteTime < ageInDays) && fi.Extension.ToUpper() != ".ZIP")
    {
        results.Add(fi[i]);
    }
}

或者使用LINQ:

results = (from fi in results
           where fi.Extension.ToUpper() != ".ZIP"
           select fi).ToList<FileInfo>();

答案 1 :(得分:1)

你试过了吗?

for (int i = 0; i < fi.Length; i++)
        {
            if (fi[i].LastWriteTime < ageInDays && fi[i].Extension != ".zip")
            {
                results.Add(fi[i]);
            }
        }

答案 2 :(得分:0)

试试这个:

      _files = Directory.GetFiles(FTPOutputDirectory);
       foreach (string fi in _files)
         {
           string fi = Path.GetExtension(f);

            if (fi.ToUpper() != ".ZIP" )
             {
                // yourWork
             }
         }

答案 3 :(得分:0)

您还可以使用lambda检查文件的扩展名

var files = di.GetFiles().Where(file => !file.FullName.EndsWith(".zip"));