Check the type of file clicked in a listbox

2019-08-17 00:30发布

问题:

How can I check the file type of an object in my listbox?

I'm returning a list of strings from an online server and simply wanting to have an event that gets fired when I click on an item that has a .folder file type at the end.

I've tried looking but can't find anything.

Can someone please provide a link or sample code so I can achieve what I would like to achieve.

回答1:

You could include the FileInfo assembly and use FileInfo.Extension.

FileInfo finfo = new FileInfo(fileName);
string fileName = finfo.Extension


回答2:

private void listBox1.SelectedIndexChanged(object sender,EventArgs e)
{
    string item ;

    item = listBox1.SelectedItem.ToString();

    if(item.EndsWith(".folder"))
    {
        //it's a .folder, raise the event or react as needed
    }
}


回答3:

If you just want the folder extension event

private void listBox1.SelectedIndexChanged(object sender,EventArgs e)
{
string file=listBox1.SelectedItem.ToString();
var ext = Path.GetExtension(file);
 if(ext ==".folder")
 {
    //raise event
 }
}


回答4:

This should work for you;

   private void listBox1.SelectedIndexChanged(object sender,EventArgs e)
    {
     string item=listBox1.SelectedItem.ToString();
     int index=item.LastIndexOf('.');
     if(index>=0)//It's a valid file
      {
       string extension=item.Substring(index+1,item.Length-index-1);
       if(extension=="folder")
       {
        MessageBox.Show("Yes it's a .folder");
       }
      }
     else if(index==-1)//Not a valid file
      {
        MessageBox.Show("The selected file is invalid.");
      }
    }