ASG
ASG

Reputation: 13

How to open a file from listview control in C#

I am trying to open a file from a ListView control on a Windows Form project in C#.

I've created the ItemActivate event on the selected item of the ListView control and verified that it works properly by adding a MessageBox.Show().

I want to add to the ItemActivate event code to open the selected item if it is a file object.

// store current directory
string currentDir = Directory.GetCurrentDirectory();
private void browserListView_ItemActivate(object sender, EventArgs e)
{
    string selectedFile = browserListView.SelectedItems[0].Text;
    // the file exists open the file.
    if (File.Exists( Path.Combine( currentDir, selectedFile ) ) )
    {
        //
        try
        {
            MessageBox.Show(currentDir + @"\" + selectedFile);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.StackTrace);
        }
    }
}

What do I need to add to the try block to replace the MessageBox.Show line in order to launch the selected file from my control?

Upvotes: 0

Views: 3185

Answers (2)

ASG
ASG

Reputation: 13

Thanks for the comments, the Systems.Diagnostics.Process.Start is what I was looking for.

  private void browserListView_ItemActivate(object sender, EventArgs e)
  {
     string selectedFile = browserListView.SelectedItems[0].Text;

     // If it's a file open it
     if (File.Exists( Path.Combine( currentDir, selectedFile ) ) )
     {
        //MessageBox.Show(currentDir + @"\" + selectedFile);
        try
        {
           System.Diagnostics.Process.Start(currentDir + @"\" + selectedFile);
        }
        catch (Exception ex)
        {
           MessageBox.Show(ex.StackTrace);
        }
     }
  }

Upvotes: 1

Norman
Norman

Reputation: 3479

System.Diagnostics.Process.Start(Path.Combine(currentDir, selectedFile));

Upvotes: 0

Related Questions