1

我正在尝试编写一个方法。

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

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

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

List应该包含具有所有子文件夹名称(不是位置,仅名称)的固定长度的字符串。但它就像图片一样:

在此处输入图像描述 提前致谢...

4

4 回答 4

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;
        }
于 2012-12-28T18:33:40.987 回答
0

更改List<String>BindingList<String>

public BindingList<string> getList()
{
    ...
   return new BindingList<string>(albums);
}
于 2012-12-28T18:22:19.047 回答
0

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

以下是一些以 pre-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<> LINQ 遍历 IEnumerable 来获取大小

于 2012-12-28T18:32:15.523 回答
0

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

n = n.Split(Path.DirectorySeparatorChar).ToString();
于 2012-12-28T18:38:56.720 回答