Sneakybastardd
Sneakybastardd

Reputation: 288

How to open file that is shown in listbox?

I have added all startup programs to a listbox. How can I open the file when I select the item and click on a button?

Listbox code:

private void readfiles()
{
    string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

    var files = Directory.GetFiles(startfolder).Where(name => !name.EndsWith(".ini"));

    foreach (string file in files)
    {
        startupinfo.Items.Add(System.IO.Path.GetFileName(file));
    }
}

Upvotes: 2

Views: 7032

Answers (4)

Rikki
Rikki

Reputation: 646

I don't know what file type you're trying to open, but this is how you can get the selected item.

Dictionary<string, string> startupinfoDict = new Dictionary<string, string>();
    private void readfiles()
    {
        string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

        var files = Directory.GetFiles(startfolder).Where(name => !name.EndsWith(".ini"));

        foreach (string file in files)
        {
            startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));
            startupinfoDict.Add(Path.GetFileNameWithoutExtension(file), file);
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (listBox1.SelectedItem != null)
        {
            string s = listBox1.SelectedItem.ToString();

            if (startupinfoDict.ContainsKey(s))
            {
                Process.Start(startupinfoDict[s]);
            }
        }
    }

Upvotes: 2

FastGeek
FastGeek

Reputation: 411

You would initiate a new process declaring the path to the file to execute / open in your button click handler:

Process.Start(@" <path to file> ");

If the selected value in the list box is the file path then:

Process.Start(<name of list box>.SelectedValue);

EDIT:

Change your foreach loop as follows:

foreach (string file in files)
{
    startupinfo.Items.Add(System.IO.Path.GetFullPath(file) + @"\" + System.IO.Path.GetFileName(file));
}

Upvotes: 0

Michel Keijzers
Michel Keijzers

Reputation: 15367

Get the currently selected list box item and assuming an application is coupled to the file('s extension use):

Process.Start(fileName);

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103535

You can get the selected item by using the SelectedValue property of the listbox.

You can open a file by using Process.Start.

Upvotes: 0

Related Questions