how to save ListBox in vb.net

how to save ListBox in vb.net
Dim files() As String
files = Directory.GetFiles("C:\", "*.mp3")

Dim file As String
For Each file In files
ListBox1.Items.Add(Path.GetFileName(file))
Next

output :
00001.mp3
00003.mp3
00005.mp3 ....

want to save all item wth Only filenam to another folder.

Comments

  • 'You can do it like this:

     Dim YourFiles As New ArrayList
    
        Dim k As Integer
        For k = 0 To ListBox1.Items.Count - 1
            YourFiles.Add(ListBox1.Items(k).ToString)
    
        Next k
        'Now you can access it like this:
    
        For k = 0 To YourFiles.Count - 1
            ListBox2.Items.Add(YourFiles.Item(k).ToString)
        Next
    

    'I prefer to use ArrayList instad of simple arrays because they are more flexible and you can inherit one arraylist inside another...

  • jdforsythejdforsythe Ohio
    edited July 2014

    How exactly do you want to save the list? Just as a list in a text file? There are a bunch of ways.

    Dim inFiles() As String = Directory.GetFiles("C:\", "*.*")
    For i As Integer = 0 To inFiles.Length - 1
        ' replace the full path in the array with just the filename
        inFiles(i) = Path.GetFileName(inFiles(i))
        ListBox1.Items.Add(inFiles(i))
    Next
    File.WriteAllLines("c:\list.txt", inFiles)
    

    Personally I'd probably use a List(Of String) instead of an array of string. It makes the For loop easier, but you have to convert the list to an array to WriteAllLines. Still, I like Lists...

    Dim inFiles As List(Of String) = Directory.GetFiles("C:\", "*.*").ToList
    For Each file As String In inFiles
        ' replace the entry in the list with just the filename
        file = Path.GetFileName(file)
        ListBox1.Items.Add(file)
    Next
    File.WriteAllLines("C:\list.txt", inFiles.ToArray)
    

    But the first option is likely the best option, since you don't have to convert to a list and then back to an array. It's unnecessary overhead.

    You can also use File.WriteAllText() to write a string to the file.

    Dim inFiles() As String = Directory.GetFiles("C:\", "*.*")
    For i As Integer = 0 To inFiles.Length - 1
        inFiles(i) = Path.GetFileName(inFiles(i))
        ListBox1.Items.Add(inFiles(i))
    Next
    File.WriteAllText("c:\list.txt", String.Join(vbCrLf, inFiles))
    

    Note that you could also write this out using many other methods, including StreamWriter

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories