Programming guides for beginner...
Any comments are welcomed....
I hope it helps!!! Thanks for drop by...

Sunday, February 20, 2011

Getting all files in directory include sub directories in vb.net

 

     As from my previous tutorial on Simple Music Player, I had mentioned that the function that I wrote to getting all songs in the directory is not possible. Now, I had found out a method by using VB.Net Stack. VB.Net Stack is a collection that stores items that being push in. It uses the concept of Last In First Out (LIFO). Although this method list out all the files in directory, as for its’ LIFO system, it will list the files from the last. (Means the last to come will be the first to out.)

Here I includes the coding that need to be changes and also a function that used to get all files.

Private Sub ListView1_DragDrop(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DragEventArgs) _
Handles ListView1.DragDrop
Dim colFiles() As String = e.Data.GetData(DataFormats.FileDrop, True)
For i = 0 To colFiles.Count - 1
Dim list As List(Of String) = GetAllFiles.GetFileList(colFiles(i))
For Each path In list
ListView1.Items.Add(System.IO.Path.GetFileName(path))
ListView2.Items.Add(path)
Next
Next
End Sub

I use loop for data that drop into listview1 is to handle when there is more than one directory being drag into listview1.


 


And here, I includes the function that used to get all files in a directory which include all sub directories.

Public Class GetAllFiles

Public Shared Function GetFileList(ByVal Dirpath As String) As List(Of String)
Dim result As New List(Of String)
Dim store As New Stack(Of String)
store.Push(Dirpath)

Do While (store.Count > 0)
Dim dir As String = store.Pop
Try
result.AddRange(Directory.GetFiles(dir, "*.mp3*"))

'change here to load music file in other formats. Not all formats are supported.
Dim directoryName As String
For Each directoryName In Directory.GetDirectories(dir)
store.Push(directoryName)
Next
Catch ex As Exception
End Try
Loop
Return result
End Function

End Class

Credited to this site where I found this method. Thanks a lot.

No comments:

Post a Comment