0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, the first option seems to be working properly for what I need. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.