获取所有子文件夹及其大小

时间:2012-12-28 18:20:17

标签: c#-4.0 combobox

我正在尝试编写方法。

public List<string> getList()
{
    string[] str;
    string no, name, size, price;
    string albumFolder = @"F:\Audio";
    char a = ' ';

    List<string> albums = new List<string>();

    albumFolder.Split(Path.DirectorySeparatorChar);
    str = albumFolder.Split(Path.DirectorySeparatorChar);

        for (int i = 0; i < str.Length; i++)
        {
            string n = str[i].ToString();
            n = n.Split(Path.DirectorySeparatorChar).ToString();
            no = (i > 8 ? "  " : "    ") + (i + 1) + "".PadRight(10, a);
            name = n.PadRight((155 - n.Length), a);
            size = "" + 512 + " MB".PadRight(20, a); // also help me finding their size
            price = "" + 80 + "".PadRight(10, a);
            albums.Add(no + name + size + price);
        }
    return albums;
}

此方法将返回List,以便我可以执行此操作:

albumList.DataSource = getList(); //albumList is a ComboBox

List应包含固定长度的字符串,其中包含所有子文件夹的名称(不是位置,仅限名称)。但它如图所示:

enter image description here 提前谢谢......

4 个答案:

答案 0 :(得分:1)

我认为这是你可能正在寻找的东西(尽管我同意有更好/更简单的方法):

public List<string> getList()
        {
            string no, name, size, price;
            string albumFolder = @"F:\Audio";
            char a = ' ';

            List<string> albums = new List<string>();

            string[] str = Directory.GetDirectories(albumFolder);

            for (int i = 0; i < str.Length; i++)
            {
                DirectoryInfo info = new DirectoryInfo(str[i]);
                no = (i > 8 ? "  " : "    ") + (i + 1) + "".PadRight(10, a);
                name = info.Name.PadRight(155, a);
                size = "" + 512 + " MB".PadRight(20, a); // also help me finding their size
                price = "" + 80 + "".PadRight(10, a);
                albums.Add(no + name + size + price);
            }
            return albums;
        }

答案 1 :(得分:0)

List<String>更改为BindingList<String>

public BindingList<string> getList()
{
    ...
   return new BindingList<string>(albums);
}

答案 2 :(得分:0)

您的代码非常复杂,并非必须如此。请使用目录和路径类,即Path.GetDirectoryName,不要手动解析。

以下是一些以NET4之前的方式遍历文件的代码:

/// <summary>
/// Walks all file names that match the pattern in a directory
/// </summary>
public static IEnumerable<string> AllFileNamesThatMatch(this string fromFolder, string pattern, bool recurse)
{
  return Directory.GetFiles(fromFolder,
                     pattern,
                     recurse ? SearchOption.AllDirectories :
                               SearchOption.TopDirectoryOnly);
}

/// <summary>
/// Walks all file names in a directory
/// </summary>
public static IEnumerable<string> AllFileNames(this string fromFolder, bool recurse)
{
  return fromFolder.AllFileNamesThatMatch("*.*", recurse);
}

你可以通过使用Sum&lt;&gt;遍历IEnumerable来获得大小。 LINQ

答案 3 :(得分:0)

从代码中删除以下行,一切正常。

n = n.Split(Path.DirectorySeparatorChar).ToString();