2013-05-04 47 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