Reading file names into variables (VB6)

Discussion in 'Software' started by ceal21c, Nov 13, 2006.

  1. ceal21c

    ceal21c Private E-2

    Hey Guys,

    I'm trying to read the names of all files stored in a particular directory and save the results to a string or an array. Can someone please help me with the VB6 code? Thanx a bunch!
     
  2. Mada_Milty

    Mada_Milty MajorGeek

    Code:
    [COLOR="Blue"]option explicit[/COLOR]     [COLOR="SeaGreen"]' Forces Explicit Variable Declaration[/COLOR]
    
    [COLOR="Blue"]dim[/COLOR] a_files()     [COLOR="SeaGreen"]' Declares an array[/COLOR]
    
    [COLOR="Blue"]dim[/COLOR] o_filesys, o_folder     [COLOR="SeaGreen"]' Declares two object variables[/COLOR]
    
    [COLOR="Blue"]dim[/COLOR] v_file, v_count     [COLOR="SeaGreen"]' Declares two variables[/COLOR]
    
    [COLOR="Blue"]const[/COLOR] c_path = [COLOR="Magenta"]"[I]pathtodirectory[/I]"[/COLOR]    [COLOR="SeaGreen"] ' Declares a constant string value containing path to the directory (add your own path)[/COLOR]
    
    [COLOR="Blue"]set[/COLOR] o_filesys = [COLOR="Red"]createobject[/COLOR] ([COLOR="Magenta"]"Scripting.Filesystemobject"[/COLOR])     [COLOR="SeaGreen"]' Creates a filesystem object[/COLOR]
    [COLOR="Blue"]set[/COLOR] o_folder = o_filesys.getfolder (c_path)     [COLOR="SeaGreen"]' Creates a folder object with specified path[/COLOR]
    
    v_count = 0     [COLOR="SeaGreen"]' Sets counter variable value to zero[/COLOR]
    
    [COLOR="Blue"]for each[/COLOR] v_file [COLOR="Blue"]in[/COLOR] o_folder.files     [COLOR="SeaGreen"]' Recurses each file in specifed directory, and sets to v_file[/COLOR]
         a_files(v_count) = v_file.name     [COLOR="SeaGreen"]' Sets file name to current index of array[/COLOR]
         v_count = v_count + 1     [COLOR="SeaGreen"]' Increments counter variable[/COLOR]
    [COLOR="Blue"]next[/COLOR]
    I believe that the above code will do the job for you. Let us know if you have any questions! Note: You'll have to change pathtodirectory to the path of the folder you wish to get the file names of.
     
  3. matt.chugg

    matt.chugg MajorGeek

    You have a couple of other options too ;) You can use the vb6 Dir() function

    Code:
    Public Function AllFiles(ByVal DirPath As String) As String()
    	Dim sFile As String
    	Dim lElement As Long
    	Dim sAns() As String
    	ReDim sAns(0) As String
    
    	sFile = Dir(DirPath, vbNormal + vbHidden + vbReadOnly + vbSystem + vbArchive)
    
    	If sFile <> "" Then
    		sAns(0) = sFile
    		Do
    			sFile = Dir
    			If sFile = "" Then Exit Do
    			lElement = IIf(sAns(0) = "", 0, UBound(sAns) + 1)
    			ReDim Preserve sAns(lElement) As String
    			sAns(lElement) = sFile
    		
    		Loop
    	End If
    	AllFiles = sAns
    End Function
    

    :( Couldn't find my code coloriser
     
  4. matt.chugg

    matt.chugg MajorGeek

    or you can use api.

    Code:
    Option Explicit
    
    Private Const MAX_PATH = 260
    Private Const FILE_ATTRIBUTE_DIRECTORY = &H10
    Private Const FILE_ATTRIBUTE_SYSTEM = &H4
    Private Const FILE_ATTRIBUTE_HIDDEN = &H2
    Private Const FILE_ATTRIBUTE_READONLY = &H1
    Private Const ERROR_NO_MORE_FILES = 18&
    
    Private Type FILETIME
        dwLowDateTime As Long
        dwHighDateTime As Long
    End Type
    
    Private Type WIN32_FIND_DATA
        dwFileAttributes As Long
        ftCreationTime As FILETIME
        ftLastAccessTime As FILETIME
        ftLastWriteTime As FILETIME
        nFileSizeHigh As Long
        nFileSizeLow As Long
        dwReserved0 As Long
        dwReserved1 As Long
        cFileName As String * MAX_PATH
        cAlternate As String * 14
    End Type
    
    Private Declare Function FindFirstFile Lib "kernel32" _
       Alias "FindFirstFileA" (ByVal lpFileName As String, _
       lpFindFileData As WIN32_FIND_DATA) As Long
       
    Private Declare Function FindNextFile Lib "kernel32" Alias _
       "FindNextFileA" (ByVal hFindFile As Long, _
       lpFindFileData As WIN32_FIND_DATA) As Long
    
    Private Declare Function FindClose Lib "kernel32" _
       (ByVal hFindFile As Long) As Long
    
    
    
    
    Public Function APIAllFiles(ByVal DirPath As String) As String()
    Dim sFile As String
    Dim lElement As Long
    Dim sAns() As String
    Dim lFirstRet As Long, lNextRet
    Dim typFindData As WIN32_FIND_DATA
    Dim sTemp As String
    Dim lAttr As Long
    
    ReDim sAns(0) As String
    
    If Right(DirPath, 1) = "\" Then DirPath = DirPath & "*.*"
    
    'Get First File
    lFirstRet = FindFirstFile(DirPath, typFindData)
    If lFirstRet <> -1 Then
        lAttr = typFindData.dwFileAttributes
    
        'Check if this is a directory.  This is probably slowing down
        'the function.  If you know you won't have subdirectories, 
        'or you want to include directories, delete this check
    
        If Not isDirectory(lAttr) Then
    
            'strip null terminator
           sAns(0) = StripNull(typFindData.cFileName)
        End If
        
        'Continue searching until all files in directory are found
        Do
            lNextRet = FindNextFile(lFirstRet, typFindData)
            If lNextRet = ERROR_NO_MORE_FILES Or _
               lNextRet = 0 Then Exit Do
            lAttr = typFindData.dwFileAttributes
                'Again, check if its a subdirectory
                If Not isDirectory(lAttr) Then
                    lElement = IIf(sAns(0) = "", 0, UBound(sAns) + 1)
                    ReDim Preserve sAns(lElement) As String
                    sAns(lElement) = StripNull(typFindData.cFileName)
                End If
        Loop
    End If
    
    FindClose lFirstRet
    APIAllFiles = sAns
    
    End Function
    
    Private Function StripNull(ByVal InString As String) As String
    
    'Input: String containing null terminator (Chr(0))
    'Returns: all character before the null terminator
    
    Dim iNull As Integer
    If Len(InString) > 0 Then
        iNull = InStr(InString, vbNullChar)
        Select Case iNull
        Case 0
            StripNull = InString
        Case 1
            StripNull = ""
        Case Else
           StripNull = Left$(InString, iNull - 1)
       End Select
    End If
    
    End Function
    
    Public Function isDirectory(FileAttr As Long) As Boolean
    
    Dim bAns As Boolean
    Dim lDir As Long
    Dim lHidden As Long
    Dim lSystem As Long
    Dim lReadOnly As Long
    
    lDir = FILE_ATTRIBUTE_DIRECTORY
    lHidden = FILE_ATTRIBUTE_HIDDEN
    lSystem = FILE_ATTRIBUTE_SYSTEM
    lReadOnly = FILE_ATTRIBUTE_READONLY
        
    isDirectory = FileAttr = lDir Or FileAttr = _
        lDir + lHidden Or FileAttr = lDir + lSystem _
        Or FileAttr = lDir + lReadOnly Or FileAttr = _
        lDir + lHidden + lSystem Or FileAttr = _
        lDir + lHidden + lReadOnly Or FileAttr = _
        lDir + lSystem + lReadOnly Or _
        FileAttr = lDir + lSystem + lHidden + lReadOnly
    
    End Function
    
     
  5. Mada_Milty

    Mada_Milty MajorGeek

    And here I am doing all mine manually! You've been holding out on us Matt! :p Do you have a browser plugin or something?
     
  6. ceal21c

    ceal21c Private E-2

    Woa! Information overload! LOL! Love IT! Thanx Alot Guys!
     
  7. matt.chugg

    matt.chugg MajorGeek

    I wrote my own mada lol, but no idea where I put it now so I guess its going on my list of things to redo lol
     
  8. Kodo

    Kodo SNATCHSQUATCH

    Boy.. in .NET you could do that in like.. oh.. ~8 lines of code including the imports system.collection.generic statement..lol. :D
    Code:
    public function GetFileNames()as List(of String)
    Dim di as new DirectoryInfo("D:\SnippetCompiler2DotNet2")
    Dim filenames as new List(of String)
    
        for each finfo as FileInfo in di.getfiles("*.*")
               filenames.add(finfo.name)
        Next
        
        return filenames
    end function
    
    Move to .NET.. you WILL thank me :)

    btw.. snippet compiler is what I use to whip up little-uns like this and make sure they work to post:
    http://www.sliver.com/dotnet/SnippetCompiler/
     
    Last edited: Nov 14, 2006
  9. matt.chugg

    matt.chugg MajorGeek

    THERE it is... ;)

    heh its actually one line lol, all he wanted was a returned array of files in a folder ;)

    Dim Files() as String = System.IO.Directory.GetFiles(folderpath)
     
  10. Kodo

    Kodo SNATCHSQUATCH

    actually, you're right.. one line of code for fileinfo :)
     
  11. matt.chugg

    matt.chugg MajorGeek

    :( lost some of my snippets files, please hold for a recursive file and folder and subfolder routine I have somewhere lol, still less lines than the vb6 ;)

    that snippet compiler looks pretty useful! especially for stuff like this where I don't have .net ides on this laptop and want to post code lol, it didn't capitalise functions for you though ;)
     
  12. Kodo

    Kodo SNATCHSQUATCH

    It's all about less code! :D
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds