Question

I have a checkedListBox; wich loads files inside a folder; to run/open when checked.

What I'm trying to achieve is to:
- Load filenames without extension into the CheckedListBox.

I can retrieve:

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

but; i just want to be retrieve: the "filename" (with or without the extention).

Something Like:

"myfile1.txt"

I was attempting to do this with folderBrowserDialog, but I have no idea on how to accomplish this.

My Current Code:

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

Can anyone point me in the right direction? Thanks in advance.

Was it helpful?

Solution

You don't need an OpenFileDialog at all, simply change the line that adds the files to

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

Just remember to add

using System.IO;

And you can also reduce everything to one line code

checkedListBox1.Items.AddRange(Directory.GetFiles(fbd.SelectedPath).Select(x => Path.GetFileName(x)).ToArray());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top