Trouble wrapping my head around loop/arraylist

Phix

Member
Joined
Apr 9, 2010
Messages
15
Location
San Jose
Programming Experience
3-5
Hey all-

New here, new to VB.net, but no stranger to programming/OOP concepts. I'm just trying to figure out how to adapt my existing knowledge of loops, data population, etc into this rather odd, plain-english language.

I'm using VB.NET, Studio 2008, if that helps.

I'm attempting to make a class of helper functions, the one I'm having problems with in particular is one that loops through a directory, storing the filenames in an ArrayList.

Incomplete code heading to what I'm after...
VB.NET:
Public Class DirReader
    Dim fList As ArrayList = New ArrayList

    Function FilesList(ByVal dir As String) As ArrayList
        For Each f As String In Directory.GetFiles(dir)
            'add to the fList array
            fList.Add(f.Substring(dir.Length, f.Length - dir.Length))
        Next
        Return fList
    End Function
End Class
It's strange though, cause if I Debug.Write out f, the Intermediate Window shows the correct result of what I'd like to add to the ArrayList. So I'm unclear somewhere along the line of how A) The .Add function works (in this case doesnt), and B) Returning the list into a variable outside this class.

As a disclaimer, I still have no idea the differences between a lot of the TLA's associated with the .NET framework, so I'm hoping this is all in the right place.
 
Well, its official. I am a n00b.

Turns out the debug was working fine. I'm so used to concatenating string with + that it returned everything fine when using the correct operator.

I'm gonna go ahead and leave this thread up for you all to throw rotten tomatoes at.
 
I have no problem with your loop per se. My first problem is the fact that you're using an ArrayList. There really is no reason to use an ArrayList from .NET 2.0 onwards. You should be pretty much always be using a generic List, unless you need something with even more functionality. If you're storing Strings then you should be using a List(Of String).

Next, if you want just the file name and not the folder path then you should either use the IO.Path.GetFileName function or else use the DirectoryInfo and FileInfo classes and the FileInfo.Name property.

Finally, if you're using .NET 3.5, you have various options for reducing your code:
VB.NET:
Dim filePaths As String() = IO.Directory.GetFiles(folderPath)
Dim fileNames As String() = Array.ConvertAll(filePaths, Function(s) IO.Path.GetFileName(s))

'If you really need a collection.
Dim files As New List(Of String)(fileNames)
VB.NET:
Dim fileNames As List(Of String) = New IO.DirectoryInfo(folderPath).GetFiles().Select(Function(fi) fi.Name).ToList()
 
Last edited:
Back
Top