Sign in to follow this  
Followers 0
j0kky

List the files in each subdirectory

5 posts in this topic

#1 ·  Posted (edited)

Probably there are billions of posts about it, but this is my version  :) 

It lists all files of the selected path and the files in its subdirectories. It can be easily converted in a function like _FileListToArray or it can be used to work on those files.

Local $path = InputBox("Path", "Enter the path", @DesktopDir, " M")
If @error Then Exit
Local $count_sub = 0, $k = 0
#forcedef $dir_array ;necessary for tidy.exe

If FileExists($path) Then ;adds or replaces "/" with "\" at the end of the path
    If StringRight($path, 1) <> "\" Then
        If StringRight($path, 1) == "/" Then
            $path = StringTrimRight($path, 1) & "\"
        Else
            $path &= "\"
        EndIf
    EndIf
Else
    MsgBox(0,"Error","The selected folder doesn't exist")
    Exit
EndIf


While 1
    Local $search = FileFindFirstFile($path & "*.*")
    If $search = -1 Then
        If @error == 1 Then ;the folder is empty
            If Not IsDeclared("dir_array") Then
                MsgBox(0, "Info", "The folder is empty")
                Exit
            EndIf
        Else ;other errors, for example an error occurs if there aren't admin rights for some folder
            If IsDeclared("dir_array") Then
                ConsoleWrite($path & " ->>> Some errors occurred with this folder" & @CRLF) ;doesn't work with #requireadmin
            Else
                MsgBox(0, "Error", "No files/directories matched the search pattern" & @CRLF & $path)
                Exit
            EndIf
        EndIf
    EndIf

    While 1
        Local $file = FileFindNextFile($search)
        If @error Then ;files are finished
            FileClose($search)
            If $count_sub <> 0 Then ;if there aren't subdirectories
                If IsDeclared("dir_array") Then ;$dir_array contains every found subdirectory, it has 2 dimensions: the first is the level, the second is the subdirectories list
                    If $count_sub > UBound($dir_array, 2) Then
                        ReDim $dir_array[UBound($dir_array) + 1][$count_sub]
                    Else
                        ReDim $dir_array[UBound($dir_array) + 1][UBound($dir_array, 2)]
                    EndIf
                Else
                    Dim $dir_array[1][$count_sub]
                EndIf
                $count_sub = 0
                Local $search = FileFindFirstFile($path & "*.*")
                While 1 ;saves all found subdirectories in the last level
                    Local $subfolder = FileFindNextFile($search)
                    If @error Then ExitLoop
                    if @extended == 1 Then
                        $dir_array[UBound($dir_array) - 1][$k] = $subfolder
                        $k += 1
                    EndIf
                WEnd
                $k = 0
                FileClose($search)
                $path &= $dir_array[UBound($dir_array) - 1][0] & "\" ;"c:\windows\system32\" --> "C:\windows\system32\drivers\"
                ExitLoop
            Else ;if the directory hasn't subdirectories
                If IsDeclared("dir_array") Then
                    If UBound($dir_array) > 1 Then ;if there is more than one level
                        if UBound($dir_array, 2) > 1 Then
                            If $dir_array[UBound($dir_array) - 1][1] <> "" Then ;if there is more than one subdirectory in the last level
                                For $i = 0 To (UBound($dir_array, 2) - 2) ;deletes the first subdirectory of the last level and replace it with the second subdirectory
                                    $dir_array[UBound($dir_array) - 1][$i] = $dir_array[UBound($dir_array) - 1][$i + 1]
                                Next
                                $dir_array[UBound($dir_array) - 1][UBound($dir_array, 2) - 1] = ""
                                $path = StringRegExpReplace($path, "[^\\]*\\$", "") ;"C:\windows\system32\drivers\" --> "c:\windows\system32\"
                                $path &= $dir_array[UBound($dir_array) - 1][0] & "\"
                                ExitLoop
                            Else
                                $path = StringRegExpReplace($path, "[^\\]*\\[^\\]*\\$", "") ;"C:\windows\system32\drivers\etc\" --> "c:\windows\system32\"
                                While 1
                                    ReDim $dir_array[UBound($dir_array) - 1][UBound($dir_array, 2)] ;deletes the last level
                                    If $dir_array[UBound($dir_array) - 1][1] = "" Then
                                        If UBound($dir_array) == 1 Then
                                            ExitLoop(3)
                                        Else
                                            $path = StringRegExpReplace($path, "[^\\]*\\$", "")
                                            ContinueLoop
                                        EndIf
                                    Else
                                        ExitLoop
                                    EndIf
                                WEnd
                                For $i = 0 To (UBound($dir_array, 2) - 2)
                                    $dir_array[UBound($dir_array) - 1][$i] = $dir_array[UBound($dir_array) - 1][$i + 1]
                                Next
                                $dir_array[UBound($dir_array) - 1][UBound($dir_array, 2) - 1] = ""
                                $path &= $dir_array[UBound($dir_array) - 1][0] & "\"
                                ExitLoop
                            EndIf
                        Else
                            ExitLoop(2)
                        EndIf
                    Else
                        If UBound($dir_array, 2) > 1 Then
                            If $dir_array[0][1] <> "" Then
                                For $i = 0 To (UBound($dir_array, 2) - 2)
                                    $dir_array[0][$i] = $dir_array[0][$i + 1]
                                Next
                                $dir_array[0][UBound($dir_array, 2) - 1] = ""
                                $path = StringRegExpReplace($path, "[^\\]*\\$", "")
                                $path &= $dir_array[0][0] & "\"
                                ExitLoop
                            Else
                                ExitLoop(2)
                            EndIf
                        Else
                            ExitLoop(2)
                        EndIf
                    EndIf
                Else
                    ExitLoop(2)
                EndIf
            EndIf
        EndIf

        if @extended = 1 Then ;it's a folder, not a file
            $count_sub += 1
            ContinueLoop
        EndIf

        #cs ENTER YOUR CODE HERE, FOR EXAMPLE:
        ConsoleWrite("File: " & $path & $file & @CRLF)
        #ce
        
        ConsoleWrite("File: " & $path & $file & @CRLF)

    WEnd
WEnd

:bye:

Edited by j0kky

Share this post


Link to post
Share on other sites



There is already a UDF function called _FileListToArrayRec().


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

BTW, the "M2" in the inputbox limits the user from putting more than 2 characters into it.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • hcI
      By hcI
      Hello everyone !
      I was looking for a parameter to set a List. Not a ComboList in ReadOnly.
      I've already found a topic about The readonly on a ComboList :
      But nothing on List
      Does someone know how to ?..
    • Vivaed
      By Vivaed
      I am trying to read all the files in a folder, then whatever file is newest, keep only that one and delete the rest.
      Example files:  (these all have version numbers embedded in them, I dont want to rely on the file name)
      Faint.exe
      Faint-v2.0.exe
      Faint-v3.0.exe
      Faint-v4.0.exe
       
      What I have so far:
      #include <File.au3> RemoveOldFiles() ConsoleWrite(FileGetVersion("C:\WB Resources\FAINT_DONT_LINK_THESE\Faint-v4.0.0.exe") &@CRLF) Func RemoveOldFiles() Local $aFileList = _FileListToArray("C:\WB Resources\FAINT_DONT_LINK_THESE\", "*.exe",$FLTA_FILES) For $i = 0 To UBound($aFileList) - 1 $aFileVersion = FileGetVersion($aFileList[$i]) ConsoleWrite($aFileList[$i] & @CRLF) ConsoleWrite($aFileVersion & @CRLF) Next EndFunc OUTPUT: >Running:(3.3.14.2):C:\Program Files (x86)\AutoIt3\autoit3_x64.exe "C:\Users\bot\ownCloud\WellBeats\Delete Old Files\delete-test.au3" --> Press Ctrl+Alt+Break to Restart or Ctrl+Break to Stop 3 0.0.0.0 a.exe 0.0.0.0 b.exe 0.0.0.0 Faint-v4.0.0.exe 0.0.0.0 4.0.0.18 <-- This is the correct file version.... +>07:34:26 AutoIt3.exe ended.rc:0 +>07:34:26 AutoIt3Wrapper Finished. >Exit code: 0 Time: 0.6647 Not sure what I am missing here?
      Thanks!
    • Rapidnxit
      By Rapidnxit
      Hi! I want to send by mail some files with a certain extension (.xml in my case). These files are located in the script folder. First, I thought to use _FileListToArrayRec function to have a list of these files. But than I don't know how to send them all at once. I know that I can attach multiple files in this way: path1;path2;path3; etc.  and so I have tried to make a string of this type with the path of the files (with a for loop) but It doesn't attach any file (only instructions.txt). How could I do? ( what I did is just an idea, if there's something better that would be great) Thanks!
      $aArrayXml = _FileListToArrayRec(@ScriptDir, "*.xml", $FLTAR_FILES) _ArrayDisplay($aArrayXml, "LIST XML") $LenghtArrayXml = UBound($aArrayXml) If ($LenghtArrayXml > 2) Then For $i = 2 To $LenghtArrayXml - 1 $temp = "&@ScriptDir&""\"&$aArrayXml[$i]&";"&"""" $XmlListFile = $XmlListFile & $temp Next EndIf $XmlListFile = StringTrimLeft($XmlListFile, 1) if($LenghtArrayXml = 2)Then $rc =_INetSmtpMailCom($s_SmtpServer, $s_FromName, $s_FromAddress, $s_ToAddress, $s_Subject, $as_Body, @ScriptDir&"\"&$aArrayXml[1]&";"&@ScriptDir&"\instructions.txt", $s_CcAddress, $s_BccAddress, $s_Username, $s_Password, $IPPort, $ssl) Else $rc = _INetSmtpMailCom($s_SmtpServer, $s_FromName, $s_FromAddress, $s_ToAddress, $s_Subject, $as_Body, @ScriptDir&"\"&$aArrayXml[1]&$XmlListFile&@ScriptDir&"\instructions.txt", $s_CcAddress, $s_BccAddress, $s_Username, $s_Password, $IPPort, $ssl) EndIf  
    • jloyzaga
      By jloyzaga
      I'd just like to find an example of a multi select list box that outputs the selections to a file. Finding lots of complex examples in examples folder and cannot find and simple ones. like simple single select list box. 
      I'm trying to put together a selection criteria. where listbox 1 has a list of environment names - when selected it will open up another control (overlay is good to cover first GUI) it then lists Applications. When selected I will use the selection to list some items from excel as a multi select list box. So are there simple examples of these that i can look at and use to create a gui that I can understand?
       
      Joe
    • Jcreator
      By Jcreator
      i used this code to take names for a text file called data and put the info of the image and it location from the data file into the gui interface but it only detect the lines with the info and it do not show the images . here is the code 
      #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <MsgBoxConstants.au3> #include <WindowsConstants.au3> #include <AVIConstants.au3> #include <TreeViewConstants.au3> #include <GuiComboBox.au3> #include <GuiTab.au3> #include <file.au3> #include <array.au3> _Main() Func _Main() Local $idTab1 $Form1 = GUICreate("Form1", 500, 334, 240, 182) $Group1 = GUICtrlCreateGroup("Group1", 20, 12, 249, 314) $idButton6 = GUICtrlCreateButton("Info", 50, 270, 185, 49) GUICtrlCreateGroup("", -99, -99, 1, 1) GUISetState(@SW_SHOW) Global $fileMPA = "C:\T-in\MPA\data.txt" FileOpen($fileMPA, 0)    Global $line1 = FileReadLine($fileMPA , 1) $imp = 0 $idTab1 = GUICtrlCreateTab(300, -3, 180, 330) GUICtrlCreateTabItem("imglist1") GUICtrlSetTip(-1, '#Region TAB1') GUICtrlSetTip(-1, '#Region LIST') Local $imglist1 = GUICtrlCreateList("", 307, 26, 164, 304) $cline =_FileCountLines($fileMPA)  While  $imp < $cline $line2 = FileReadLine($fileMPA , $imp + 2)  $imp = $imp + 7 if $line2 = ""  then     ExitLoop    else  GUICtrlSetData(-1, ""& $line2 &"", "")  endif WEnd GUICtrlCreateTabItem("imagelist2") GUICtrlSetTip(-1, '#Region TAB2') GUICtrlCreateTabItem("imagelist3") GUICtrlSetTip(-1, '#Region TAB3') While 1     $Msg = GUIGetMsg()     Select         Case $Msg = $GUI_EVENT_CLOSE             Exit             Global $whatnow = GUICtrlRead($imglist1) Case $Msg = $idButton6             $imp2 = 0              While  $imp2 < 30 $line2 = FileReadLine($fileMPA ,$imp2 + 2) $line3 = FileReadLine($fileMPA , $imp2 + 3) $line7 = FileReadLine($fileMPA , 7)  $imp2 = $imp2 + 7 if $line2 = ""  then  ExitLoop             If GUICtrlRead($imglist1) = ""& $line2 &""  Then MsgBox($MB_SYSTEMMODAL, "img info" , $line3)                WEnd             EndSelect $imp2 = 0              While  $imp2 < 30 $line2 = FileReadLine($fileMPA ,$imp2 + 2) $line3 = FileReadLine($fileMPA , $imp2 + 3) $line7 = FileReadLine($fileMPA , 7)  $imp2 = $imp2 + 7     Select Case GUICtrlRead($imglist1) = ""& $line2 &"" if $line2 = "" then ExitLoop     $Pic1 = GUICtrlCreatePic(""& $line7 &"", 185, 28, 233, 230) If GUICtrlRead($imglist1) then  ExitLoop EndSelect WEnd     WEnd  EndFunc   ;==>_Main the data.txt file content is 
      Hibiscus Hibiscus is a hardy perennial which grows in variety of colors, sizes and fragrances. Actually they are tropical flowers which require ample sunlight and moisture to grow well. These flowers start blooming in late spring and continuously bloom through July and August. C:\T-in\IMG\2.jpg Lilies There are different types of lily flowers which bloom in August including water lilies, tiger lilies and gold band lilies. Tiger lilies generate orange flowers having black spots. This lily blooms in delayed July and beginning of August. Gold band lily produce exotic white blooms. All varieties of lilies need enough space to grow and protection from summer sun. C:\T-in\IMG\1.jpg Turtlehead Growing in humid areas, turtleheads are small flowers which bloom from July to September. They mostly produce flowers of white and pink color. C:\T-in\IMG\3.jpg Hydrangea These are ever green bushes which produce flowers in different colors including white, purple, blue and pink. They are easy to grow bushes and can grow 3 to 10 feet tall. They require morning sun to grow but they should be protected from noon and afternoon sun. C:\T-in\IMG\4.jpg Dahlias August proves to be the peak blooming season for dahlias. Dahlias come in colors like white, orange, yellow, red and purple. They can tolerate all types of soil and require full sun to grow.