Search code examples
c#listviewwindows-forms-designerfileinfodirectoryinfo

How to make difference between FileInfo and DirectoryInfo in a file explorer in list view


I would like to make a file explorer with Windows Forms, i already have done a few things, but when i would like to use the DoubleClick event of my ListView I dont know how to code that file explorer needs to act differently when I make the doubleclick on a file or a folder.

My goal is:

  1. Clicking on a file - Loads its text into a TextBox
  2. Clicking on a directory - Opens it and loads it into the listview.

I know how to do 1. and 2. as well, I just don't know how can I make my DoubleClick function know what the selected item in ListView was 1. or 2.

I build my ListView like this:

private void miOpen_Click(object sender, EventArgs e)
{
    InputDialog dlg = new InputDialog();
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        DirectoryInfo parentDI = new DirectoryInfo(dlg.Path);
        listView1.Items.Clear();
        try
        {
            foreach (DirectoryInfo df in parentDI.GetDirectories())
            {
                ListViewItem lvi = new ListViewItem(new string[] { 
                df.Name, df.Parent.ToString(), 
                df.CreationTime.ToShortDateString(), df.FullName });
                listView1.Items.Add(lvi);
            }

            foreach (FileInfo fi in parentDI.GetFiles())        
            {                                                   
                ListViewItem lvi = new ListViewItem(new string[] { 
                fi.Name, fi.Length.ToString(), 
                fi.CreationTime.ToShortDateString(), fi.FullName } );
                listView1.Items.Add(lvi);
            }
        }
        catch { }
    }
}

Solution

  • Add the DirectoryInfo or the FileInfo objects to the Tag property of the ListViewItem. I.e

    ...
    var lvi = new ListViewItem(new string[] { 
        df.Name,
        df.Parent.ToString(), 
        df.CreationTime.ToShortDateString(),
        df.FullName
    });
    lvi.Tag = df;
    listView1.Items.Add(lvi);
    ...
    

    or for the file info:

    lvi.Tag = fi;
    

    Then, after having selected an item in the listview:

    private void btnTest_Click(object sender, EventArgs e)
    {
        // Show the first item selected as an example.
        if (listView1.SelectedItems.Count > 0) {
            switch (listView1.SelectedItems[0].Tag) {
                case DirectoryInfo di:
                    MessageBox.Show($"Directory = {di.Name}");
                    break;
                case FileInfo fi:
                    MessageBox.Show($"File = {fi.Name}");
                    break;
                default:
                    break;
            }
        }
    }