Search code examples
c#winformschecklistbox

Opening outside files in C# WinForms


So basically what I'm trying to accomplish is being able to select a file from a displayed list and open that file. Right now I have it set up in a CheckBoxList that displays the .docx, .mov, and .txt files that exist in the selected folder. The problem is I can't get it to open the file. I've seen most people suggesting-

Process.Start(filename);

But the problem with that is that it requires a specific file name and I'm trying to pull that name from a variable. Any ideas?
Here's my current code -

private void Form1_Load(object sender, EventArgs e)
    {
        const string path = @"C:\Users\Haxelle\Documents\Journal";
        List<string> extensions = new List<string> { "DOCX", "MOV", "TXT" };

        string[] files = GetFilesWithExtensions(path, extensions);
        ckbEntry.Items.AddRange(files);
    }

    private string[] GetFilesWithExtensions(string path, List<string> extensions)
    {
        string[] allFilesInFolder = Directory.GetFiles(path);
        return allFilesInFolder.Where(f => extensions.Contains(f.ToUpper().Split('.').Last())).ToArray();
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        CheckedListBox.CheckedItemCollection selectedFiles = ckbEntry.CheckedItems;


    }

Trying to open file in btnOpen_Click


Solution

  • It seems like all you are missing is iterating over the selected files names and opening them. Since the CheckedItemCollection.Item is typed as object, you will need to cast the items, which can be done using LINQ's Cast function.

    private void btnOpen_Click(object sender, EventArgs e)
    {
        CheckedListBox.CheckedItemCollection selectedFiles = ckbEntry.CheckedItems;
        foreach (var filename in selectedFiles.Cast<string>()) {
            Process.Start(filename);
        }
    }