Search code examples
vb.net

List files in ListBox without filepath in Visual Basic


I'm trying to list files into a ListBox with

Dim files() As String = IO.Directory.GetFiles(CurDir, "*.txt")

For the ListBox I use

ListBox1.Items.AddRange(files)

But it returns with a full path, how would I be able to only get the filename?


Solution

  • There are multiple options. If you wanted to stick as closely as possible to what you already have, you can call Path.GetFileName for each file path, e.g.

    Dim filePaths = Directory.GetFiles(CurDir, "*.txt")
    Dim fileNames = Array.ConvertAll(filePaths, Function(s) Path.GetFileName(s))
    
    ListBox1.Items.AddRange(fileNames)
    

    I would go with a slightly different approach though. I'd suggest that you use DirectoryInfo, FileInfo and data-binding:

    Dim folder = New DirectoryInfo(CurDir)
    Dim files = folder.GetFiles("*.txt")
    
    With ListBox1
        .DisplayMember = "Name"
        .ValueMember = "FullName"
        .DataSource = files
    End With
    

    The user will now see just the file names, but you can get the full path for the selected item from the SelectedValue property.