2013-05-04 45 views
1

我有一個checkedListBox;在某個文件夾內加載文件;在檢查時運行/打開。 我想要實現的是在列表框中加載文件;但沒有路徑。C#folderBrowserDialog + openFileDialog checkedListBox上的隱藏路徑

即:

"C:\Folder1\anotherfolder\myfile1.txt" 

換言之;我只想顯示:文件名(有或沒有擴展名)。

即:

"myfile1.txt" 

的代碼我使用:

//... 
    private string openFileName, folderName; 
    private bool fileOpened = false; 
//... 

     OpenFileDialog ofd = new OpenFileDialog(); 
     FolderBrowserDialog fbd = new FolderBrowserDialog(); 

     if (!fileOpened) 
     { 
      ofd.InitialDirectory = fbd.SelectedPath; 
      ofd.FileName = null; 


      fbd.Description = "Please select your *.txt folder"; 
      fbd.RootFolder = System.Environment.SpecialFolder.MyComputer; 
      if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
      { 
       string foldername = fbd.SelectedPath; 
       foreach (string f in Directory.GetFiles(foldername)) 
       checkedListBox1.Items.Add(f); 
      } 

我試過幾種方法... 只有具備的FolderBrowserDialog似乎是不可能的。 但是,這個,應該通過結合OFD和FBD以某種方式工作(理論上)。 我只是不知道。因爲我對C#編程頗爲「新鮮」。 任何想法,如果可能的話;或者它是如何完成的?

在此先感謝;

裏卡多

回答

1

你並不需要一個OpenFileDialog可言,簡單的改變,增加了文件以

checkedListBox1.Items.Add(Path.GetFileName(f)); 

行只記得添加

using System.IO; 

而且你也可以減少一切爲一行代碼

checkedListBox1.Items.AddRange(Directory.GetFiles(fbd.SelectedPath).Select(x => Path.GetFileName(x)).ToArray()); 
+0

checkedListBox1.Items.AddRange(Directory.GetFiles(fbd.SelectedPath).Select(x => Path.GetFileName(x))。ToArray()); 這個對我很好! 第一個只顯示路徑;而不是文件名。 現在我需要學習多一點,所以我可以理解代碼^^ 我不能投票(尚未高度排名);但我很滿意你的答案。 謝謝 – Richard 2013-05-04 12:47:55

+0

很高興爲您提供幫助,加深對「Lambda表達式」的理解搜索以及IEnumerable 擴展方法 – Steve 2013-05-04 13:06:04