2014-01-14 89 views
0

我有以下代碼來使用驅動器(RootDrive)和目錄填充Treeview。 但是,如何在每個循環之後清除目錄集合?現在發生的是全部目錄全部驅動器被添加到每個驅動器。 當我在Finally語句中使用directories.Clear()時,沒有添加到每個驅動器的目錄。使用條目填充後清除ObservableCollection

static public ObservableCollection<GetDrive> RootDrive = new ObservableCollection<GetDrive>(); 

public MainWindow() 
{ 
    InitializeComponent(); 

    ObservableCollection<GetDirectory>directories = new ObservableCollection<GetDirectory>(); 

    foreach (DriveInfo di in DriveInfo.GetDrives()) 
    { 
     try 
     { 
      foreach (string s in Directory.GetDirectories(di.Name)) 
      { 
       directories.Add(new GetDirectory(s)); 
      }    
     } 

     catch (IOException) //drive is not ready, e.g. DVD drive 
     { 

     } 

     finally 
     { 
      RootDrive.Add(new GetDrive(di.Name, directories)); 
      directories.Clear(); 
     } 
    } 
} 

} 

}

+0

清除剛纔填充的集合有什麼意義? – markmnl

+0

要點是用新項目填充集合 –

回答

1

簡而言之,使用本地變量。你濫用finally指令。

static public ObservableCollection<GetDrive> RootDrive = new ObservableCollection<GetDrive>(); 

public MainWindow() 
{ 
    InitializeComponent(); 

    foreach (DriveInfo di in DriveInfo.GetDrives()) 
    { 
     ObservableCollection<GetDirectory>directories = new ObservableCollection<GetDirectory>(); 
     try 
     { 
      foreach (string s in Directory.GetDirectories(di.Name)) 
      { 
       directories.Add(new GetDirectory(s)); 
      }    
     } 
     catch (IOException) //drive is not ready, e.g. DVD drive 
     { 
      // Handle it? 
     }  
     RootDrive.Add(new GetDrive(di.Name, directories)); 
    } 
} 
+0

謝謝,應該看到這個我自己 –

0

我認爲你必須更改代碼位和第一個for循環之後添加明確的方法。像下面...

static public ObservableCollection<GetDrive> RootDrive = new ObservableCollection<GetDrive>(); 

public MainWindow() 
{ 
    InitializeComponent(); 


    foreach (DriveInfo di in DriveInfo.GetDrives()) 
    { 
     try 
     { 
      directories.Clear(); 
      foreach (string s in Directory.GetDirectories(di.Name)) 
      { 
       directories.Add(new GetDirectory(s)); 
      }    
     } 

     catch (IOException) //drive is not ready, e.g. DVD drive 
     { 

     } 

     finally 
     { 
      RootDrive.Add(new GetDrive(di.Name, directories)); 

     } 
    } 
} 

} 
+0

哇,這很快..但它沒有工作。現在只有最後一個驅動器的目錄被添加到每個驅動器。 –

+1

您能否寄給我完整的資料來源如果我有完整的資料來源,我可以幫助您在這件事情上肯定的來源 – Nil23