How to open file location from list view item using context menu strip?


New member
Mar 7, 2012
London, United Kingdom, United Kingdom
Programming Experience
Here is list of things I want to do:

Display context menu strip only when mouse is over the item and right clicked on it, the code I have for that is this:

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
            if (listView1.SelectedItems.Count == 0)
                e.Cancel = true;

        private void contextMenuStrip1_MouseClick(object sender, MouseEventArgs e)
            if (e.Button == MouseButtons.Right)
                Point pt = listView1.PointToScreen(e.Location);

The problem about this code is longest the item is selected it will display the menu strip, what I don't want is the context menu strip shouldn't show up unless directly right clicked on the item.

I have 3 options on the context menu strip, open, open file location and properties. If user right clicks the item and says open, its should ask the user what do you want to open it with using Windows explorer! For the open file location, I came up with this:

Process.Start("explorer.exe", "I need filepath from listview item");

That does open the custom location, however since there is going to be lots of files in the list view, I need the program to get the file location it self.

The implementation I have for the scanning files and displaying them on list view is:

private void button1_Click(object sender, EventArgs e)


            string[] directories = new string[] { 

            string[] extensions = new string[] { "*" };

            foreach (var dir in directories)
                var dirInfo = new DirectoryInfo(dir);
                foreach (var ext in extensions)
                    foreach (var fileInfo in dirInfo.GetFiles(ext))
                        listView1.Items.Add(new ListViewItem(new string[] { fileInfo.Name, Path.GetDirectoryName(fileInfo.FullName) + @"\", SizeUnit.FileSizeToString(fileInfo.Length) }));

Hope that can help you a bit, if you need to know more ask, I also have a code to calculate the size of the file, i didn't insert is because I don't think you will need it really. If anything is not clear plz do ask and thank you very much all helps are appreciated.
Don't set the ContextMenuStrip property of the ListView.
Then from ListView MouseClick event handler check which button was clicked and use ListView.GetItemAt method.
If an item clicked store the information you need from the item (use a private field) and show the context menu.
For Click handler of context menu item use the information you stored to perform its action.
Top Bottom