简体   繁体   中英

Populate ComboBox with Each FileType From Directory

Basically, I have a ComboBox which I want to populate with File Extensions from a specific Directory .

Currently, I'm using:

Dim dir = "C:\"
For Each file As String In System.IO.Directory.GetFiles(dir)
   cmb_FileTypes.Items.Add(System.IO.Path.GetExtension(file))
Next

This doesn't work properly because it basically loads all the extensions for all the files in the directory. I want it so that it shows each ONE file type. for instance, if there are 10 files:

  • File1.jpg
  • File2.jpg
  • File3.png
  • File4.mp3
  • File5.mp3
  • File6.dat
  • File7.dat
  • File8.tif
  • File9.jpg
  • File10.mp3

Out of these 10 Files, there are 6 file extensions that are different file extensions:

  • Jpg
  • Png
  • Mp3
  • Dat
  • tif

How do I load each 1 one these file extensions into the ComboBox rather than just repeating it?

使用LINQ在一个批量中添加组合框的所有扩展。

cmb_FileTypes.Items.AddRange((From name In Directory.GetFiles(dir) Select Path.GetExtension(name).Replace(".", "") Distinct).ToArray())

You could use LINQ to group the extensions

For Each file As String In Directory.GetFiles(dir).[Select](Function(p) Path.GetExtension(p)).Distinct().OrderBy(Function(p) p).ToList()
    cmb_FileTypes.Items.Add(System.IO.Path.GetExtension(file))
Next

or you can create a method which returns a List<string> containing unique extensions.

Public Function UniqueExtensions(filenames As String()) As List(Of String)
    Dim extSet As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)
    For Each file As String In filenames
        extSet.Add(System.IO.Path.GetExtension(file))
    Next
    Return extSet.ToList()
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM