如何在目录中查找不同类型的文件?

时间:2010-12-21 20:41:44

标签: c# filesystems

public List<string> MapMyFiles()
{
    List<FileInfo> batchaddresses = new List<FileInfo>();
    foreach (object o in lstViewAddresses.Items)
    {
        try
        {
            string[] files = Directory.GetFiles(o.ToString(), "*-E.esy");
            files.ToList().ForEach(f => batchaddresses.Add(new FileInfo(f)));
        }
        catch
        {
            if(MessageBox.Show(o.ToString() + " does not exist. Process anyway?",
                       "Continue?", MessageBoxButtons.YesNo)
                == DialogResult.Yes) { }
            else
            {
                Application.Exit();
            }
        }
    }

    return batchaddresses.OrderBy(f => f.CreationTime)
             .Select(f => f.FullName).ToList();
}

我想不仅添加到数组

  

.ESY

但也

  

“P-的.csv”

我该怎么做?

5 个答案:

答案 0 :(得分:1)

或者只是包含更多过滤器并一起选择它们:

var filters = new[] { "*-E.esy", "*p-.csv" };
var files = filters.SelectMany(f => Directory.GetFiles(o.ToString(), f));
// .. etc.

答案 1 :(得分:0)

我认为你必须使用不同的通配符多次迭代。

答案 2 :(得分:0)

假设您的代码适用于一组通配符......

然后在以下几行之后:

string[] files = Directory.GetFiles(o.ToString(), "*-E.esy");
files.ToList().ForEach(f => batchaddresses.Add(new FileInfo(f)));

添加以下内容:

files = Directory.GetFiles(o.ToString(), "*p-.csv");
files.ToList().ForEach(f => batchaddresses.Add(new FileInfo(f)));

答案 3 :(得分:0)

public List<string> MapMyFiles()
{
    List<FileInfo> batchaddresses = new List<FileInfo>();
    foreach (object o in lstViewAddresses.Items)
    {
        DirectoryInfo di = new DirectoryInfo(o);
        if (!di.Exists && MessageBox.Show(o.ToString() + " does not exist. Process anyway?", "Continue?", MessageBoxButtons.YesNo) != DialogResult.Yes)
            Application.Exit();

        (new List<string>(new[]{ "*-E.esy", "*p-.csv" })).ForEach(filter => {
            (new List<string>(di.GetFiles(filter))).ForEach(file => {
                batchaddresses.Add(new FileInfo(file));
            });
        });
    }

    return batchaddresses.OrderBy(f => f.CreationTime).Select(f => f.FullName).ToList();
}

这是我的出价;添加了目录检查。

答案 4 :(得分:0)

 try
 {
     foreach (string searchPattern in searchPatterns)
     {
         string[] files = Directory.GetFiles(o.ToString(), searchPattern);
         files.ToList().ForEach(f => batchaddresses.Add(new FileInfo(f)));
     }
 }