【问题标题】:Load filenames without extension to CheckedListBox将不带扩展名的文件名加载到 CheckedListBox
【发布时间】:2013-05-04 11:36:19
【问题描述】:

我有一个checkedListBox;将文件加载到文件夹中;选中时运行/打开。

我想要实现的是:
- 将不带扩展名的文件名加载到 CheckedListBox 中。

我可以找回:

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

但是;我只想被检索:“文件名”(有或没有扩展名)。

类似的东西:

"myfile1.txt"

我试图用 folderBrowserDialog 来做到这一点,但我不知道如何做到这一点。

我当前的代码:

//...
    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);
            }

谁能指出我正确的方向? 提前致谢。

【问题讨论】:

    标签: c# filenames openfiledialog checkedlistbox folderbrowserdialog


    【解决方案1】:

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

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

    记得添加

    using System.IO;
    

    您还可以将所有内容简化为一行代码

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

    【讨论】:

    • 很高兴为您提供帮助,加深您对“Lambda 表达式”和 IEnumerable 扩展方法的理解
    猜你喜欢
    • 2016-09-06
    • 1970-01-01
    • 2015-03-11
    • 2014-09-06
    • 2011-06-15
    • 2018-01-11
    • 2011-10-02
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多