2012-12-28 82 views
1

我想寫一個方法。 (僅適用於不位置,名稱)獲取所有子文件夾及其大小

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

List應該包含固定長度的所有subsfolder的名稱字符串:

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,這樣我可以做到這一點。但是,這樣做的圖片:提前更改List<String>

enter image description here 謝謝...

回答

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

是的。但大小和價格列未正確對齊。看到[圖片](http://www.4shared.com/photo/Pwrbq2g0/a_2.html) –

+0

嗨,布賴恩,是的,你需要使用一個單體字體/固定寬度的字體來實現你想要的外觀。另外,我在「名稱」字段的答案中修正了一個小錯字 - 您不想從填充中減去長度。祝你好運! – sgeddes

0

你的代碼是非常複雜的,並不一定如此。請使用Directory和Path類,即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); 
} 

您可以通過使用金額<> LINQ走了IEnumerable得到大小

0

從您的代碼中刪除以下行,一切正常。

n = n.Split(Path.DirectorySeparatorChar).ToString(); 
相關問題