C#folderBrowserDialog + openFileDialog在checkedListBox上隐藏路径

时间:2013-05-04 11:36:19

标签: c# path openfiledialog folderbrowserdialog

我有一个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 个答案:

答案 0 :(得分:1)

根本不需要OpenFileDialog,只需更改添加文件的行

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

请记得添加

using System.IO;

您还可以将所有内容缩减为一行代码

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