如何使用里面的文件返回我的文件夹列表?

时间:2012-04-12 13:19:43

标签: c# .net system.io.fileinfo

我想知道如何使用里面的文件返回我的文件夹列表。

因为我无法返回两个列表......并且无法将两种类型都放在列表中。

    public List<DirectoryInfo> GetTopFolders()
    {
        List<DirectoryInfo> Folders = new List<DirectoryInfo>();
        List<FileInfo> Files = new List<FileInfo>();

        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("C://inetpub//wwwroot//Files//");
        di.GetDirectories();
        System.IO.FileInfo[] fiArr = di.GetFiles();

        foreach (DirectoryInfo t in di.GetDirectories())
        {
            Folders.Add(t);
            foreach (FileInfo f in di.GetFiles())
            {
                Files.Add(f);
            }
        }
        return Folders;
    }

这是我实际使用的代码。

3 个答案:

答案 0 :(得分:5)

嗯,FileInfo和DirectoryInfo都继承自FileSystemInfo。因此,您可以维护该类型的列表,并将整个批次返回:

public List<FileSystemInfo> GetTopFoldersAndFiles()
{
    List<FileSystemInfo> FilesAndFolders = new List<FileSystemInfo>();

    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("C://inetpub//wwwroot//Files//");
    di.GetDirectories();
    System.IO.FileInfo[] fiArr = di.GetFiles();

    foreach (DirectoryInfo t in di.GetDirectories())
    {
        FilesAndFolders.Add(t);
        foreach (FileInfo f in di.GetFiles())
        {
            FilesAndFolders.Add(f);
        }
    }
    return FilesAndFolders;
}

当然,您可能需要在代码中进行一些条件处理,您可以根据每个项目的类型使用此对象。

答案 1 :(得分:3)

你可以使用两元组。见Tuple.Create on msdn

public Tuple<List<DirectoryInfo>,List<FileInfo>> GetTopFolders()
{
    List<DirectoryInfo> Folders = new List<DirectoryInfo>();
    List<FileInfo> Files = new List<FileInfo>();

     /* All your other code here */
     /* Removed for brevity*/
    foreach (DirectoryInfo t in di.GetDirectories())
    {
        Folders.Add(t);
        foreach (FileInfo f in di.GetFiles())
        {
            Files.Add(f);
        }
    }
    return Tuple.Create(Folders, Files);
}

你这样使用它:

var fileAndFolders = GetTopFolders()
fileAndFolders.Item1 //will be your folders of type List<DirectoryInfo>
fileAndFolders.Item2 //will be your folders of type List<FileInfo>

答案 2 :(得分:1)

您可以使用Dictionary<DirectoryInfo, List<FileInfo>>

private Dictionary<DirectoryInfo, List<FileInfo>> GetTopFolders()
{
    Dictionary<DirectoryInfo, List<FileInfo>> r = new Dictionary<DirectoryInfo, List<FileInfo>>();


    DirectoryInfo di = new DirectoryInfo("C://inetpub//wwwroot//Files//"); 
    di.GetDirectories();

    r.Add(di, di.GetFiles().ToList());

    foreach (DirectoryInfo t in di.GetDirectories()) 
    {
        r.Add(t, t.GetFiles().ToList());
    } 

    return r; 
}

然后你可以列出你的文件夹和文件:

StringBuilder sb = new StringBuilder();

foreach (KeyValuePair<DirectoryInfo, List<FileInfo>> item in GetTopFolders())
{
    sb.AppendLine(item.Key.FullName);

    foreach (FileInfo file in item.Value)
    {
        sb.AppendLine("\t" + file.Name);
    }
}

Console.WriteLine(sb.ToString());