I need to get a list of files from a directory and store them in an array of some form so I can modify their names to display them in a TreeView. How would one do this?
I’ve had to do this several times, and my solution has been to use the dir command to write the directory to a temp file, then use the temp file to load the array/dropdown/whatever. Sorry I can’t be more specific, but the code I’ve created is on my work computer.
I don’t particularly care this approach, though, because a) I dislike temp files on principle, and b) you have to go through some gyrations to make sure the dir finishes before the program proceeds. Perhaps someone will be along with a more elegant solution; if not, I’ll respond in more detail at a later time.
Look at FindFirst file and FindNextFile WIN32 functions.
You guys are making this harder than it needs to be. =) Just use the VB Dir function in a loop to get the directory listing like this:
Dim sFile As String
sFile = Dir("c:\")
Do While (Len(sFile) > 0)
Debug.Print sFile
sFile = Dir
Loop
Inside the loop you can do whatever you’d like with the file name - you could add it right to the treeview or store it in an array or a collection for later use.
I like these API functions for this sort of thing, also.
Look here for an example.
Parallax’s suggestion is probably simpler. API call performance is probably better. At least it was in my own experience of using it.
Call me lazy if you like, but more often than not I just use the objects exposed by the Microsoft Scripting Runtime (FileSystemObject). Saves a lot of hassle, but whether you can use them depends on your target deployment environment.
If I’m only after filenames then FindFirstFile/FindNextFile just seems like too much effort.