按创建顺序获取文件列表

时间:2010-12-21 18:10:25

标签: c#

我目前正在将不同目录中的文件列表读入LIST:

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

            }

我将如何按列表中的创建日期对它们进行排序?

3 个答案:

答案 0 :(得分:2)

尝试使用FileInfo对象并按CreationTime属性排序,然后将其作为路径FullName返回

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 { }
    }

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

答案 1 :(得分:2)

List<string> pathsToSearch = ...
List<string> batchaddresses = pathsToSearch
    .SelectMany(p => new DirectoryInfo(p).GetFiles("*-E.esy"))
    .OrderBy(f => f.CreationTime)
    .Select(f => f.Name)
    .ToList();

答案 2 :(得分:1)

以下是工作样本。

顺便说一句,我尝试将DirectoryInfo.GetFiles替换为DirectoryInfo.EnumerateFiles来提高效果。但程序时间似乎完全相同(只有几毫秒的差异)。有人可以解释一下吗?

    GetOrderedFileList2(new DirectoryInfo(@"C:\Program Files\"));

    public List<string> GetOrderedFileList2(DirectoryInfo dirInfo)
    {
        using (new StopWatchPrinter())
        {
            List<string> orderedFileList = dirInfo.EnumerateFiles("*.dll", SearchOption.AllDirectories)
                .OrderBy(f => f.CreationTime)
                .Select(f => f.Name)
                .ToList();

            Debug.Print(string.Format("\n\n *** EnumerateFiles() - found: {0} files ***", orderedFileList.Count));

            return orderedFileList;
        }
    }