AmarokStudios

Include Full Directory

1 post in this topic

Good afternoon AutoIt community!,

I was on Stackoverflow the other day and came across this question: How To Include Files From A Directory. This got me thinking... There has to be a way to do it... After a bunch of research, I wasn't able to find anything. So, I created this UDF to dynamically include every file from the directory. Of course, there are some bugs that I'd like to fix eventually, but for the most part, it works. Simply call the main function (Shown below) right after the rest of the includes before any of your actual code, and the UDF will include all of the au3 files in the specified directory. Without further ado, here is the _includeDir UDF and how to use it!

 

_includeDir.au3

Spoiler
#cs
        Name: _includeDir.au3
        Developer: Timothy Bomer
        Copyright: Amarok Studios LLC 2016
        Version: 1.0
        Description:
            The purpose of this UDF is to dynamically include all files inside of a folder.
            It works for the most part, but I am still working on a couple of bugs.
#CE


#Include <File.au3>


Global $mainUDF = "IncludeDirUDF"
Global $includeLib = $mainUDF & "\" & "loadIncludes.au3"
Global $tempLib = $mainUDF & "\" & "lib.txt"
Global $includeRewrite = $mainUDF & "\rewrite.au3"
Global $iDirHolder = ""


Func _includeDir($iDir, $lineToInc = 1, $restart = True)
    If (checkInclude()) = 1 Then
        FileDelete($tempLib)
        return
    EndIf
    If NOT (FileExists($iDir)) Then
        MsgBox(16,"Directory Doesn't Exists | _includeDir","The directory " & $iDir & " does not exist!")
        return 0
    EndIf
    $iDirHolder = $iDir
    initializeCheck()
    ; MsgBox(0,"Include Directory", "Attempting to include: " & $iDir)
    populateLib($iDir)
    populateIncLib()
    finalize($lineToInc, $restart)
EndFunc

Func checkInclude()
    FileOpen(@ScriptName, 0)
    For $i = 1 to _FileCountLines(@ScriptName)
        $checkLine = FileReadLine(@ScriptName, $i)
        If ($checkLine = '#Include "IncludeDirUDF\loadIncludes.au3"') Then
        return 1
        EndIf
    Next
EndFunc

; START Initialize Check
Func initializeCheck()
    ; MsgBox(0,"Checking. . .", "Is this initialized?")
    If (FileExists($mainUDF)) Then
        If NOT (FileExists($includeLib)) Then
            isError(2)
            return
        EndIf

        ; MsgBox(0,"Initialized","The UDF has been initialized")
    Else
        isError(1)
        return
    EndIf
EndFunc
; END Initialize Check

; START Library Population
Func populateLib($iDir = $iDirHolder)
    ; MsgBox(0,"Populating","Attempting to populate the library")
    If (FileExists($tempLib)) Then
        ; MsgBox(0,"Temp File Found","The temporary library file has been found. Attempting to populate.")
        $tLibCont = _FileListToArray(@ScriptDir & "\" & $iDir & "\", "*")
        $iDirSize = $tLibCont[0]
        ; MsgBox(0,"Size of Included Directory", $iDir & " contains " & $iDirSize & " files to include!")
        $writeLib = FileOpen($tempLib, 1)
        While $iDirSize > 0
            FileWriteLine($writeLib, '#Include "..\' & $iDir & '\' & $tLibCont[$iDirSize] & '"')
            $iDirSize -= 1
        WEnd
        FileClose($writeLib)
    Else
        isError(3)
        return
    EndIf
EndFunc
; END Library Population

; START Include Library Population
Func populateIncLib()
    ; MsgBox(0,"Rewriting. . .", "Attempting to re-write the include library")
    #CS
    If (FileExists($includeLib)) Then
        FileDelete($includeLib)
        _FileCreate($includeLib)
    EndIf
    #CE
    FileOpen($tempLib, 0)
    For $i = 1 to _FileCountLines($tempLib)
        $line = FileReadLine($tempLib, $i)
        $reWriteLib = FileOpen($includeLib, 9)
        FileWriteLine($reWriteLib, $line)
        FileClose($reWriteLib)
    Next
    FileClose($tempLib)
EndFunc
; END Include Library Population

; START Finalize
Func finalize($lineToInc, $restart)
    _FileWriteToLine(@ScriptName, $lineToInc, '#Include "IncludeDirUDF\loadIncludes.au3"', False)
    If ($restart = True) Then
        runFile(@ScriptName)
    EndIf
    exit
    return
EndFunc


Func runFile($rFile)
    $file_loc = $rFile

    If @Compiled = 1 Then
         $file_exe = FileGetShortName(@AutoItExe & ' /AutoIt3ExecuteScript "' & $file_loc & '"')
         Run($file_exe)
    Else
         $file_au3 = FileGetShortName($file_loc)
         Run(@AutoItExe & " " & $file_au3, "", @SW_HIDE)
     EndIf
EndFunc

; START Error Reporting
Func isError($eFlag = "", $eMessage = "There was an error!")
    If ($eFlag = "") Then
        ; MsgBox(16,"ERROR", $eMessage)
        Exit
    EndIf

    If ($eFlag = 1) Then
        ; MsgBox(16,"Not Initialized","This UDF has not been initialized")
        DirCreate($mainUDF)
        Sleep(250)
        initializeCheck()
        return
    ElseIf ($eFlag = 2) Then
        ; MsgBox(16,"Missing File","Missing the include library!")
        _FileCreate($includeLib)
        initializeCheck()
        return

    ElseIf ($eFlag = 3) Then
        ; MsgBox(16,"Missing File", "Missing the temporary library! Creating it now!",3)
        _FileCreate($tempLib)
        populateLib()
        return
    EndIf
EndFunc
; END Error Reporting

 

 

Download this code (_includeDir.au3 attached as well) and place it into the directory with your current script. Next, include it in your main file. For now, I'm going to be using one called Example.au3.

 

#Include "_includeDir.au3"

Now, include whatever else you're going to be including in this script, then call the _includeDir function. NOTE: THIS MUST BE CALLED AT THE TOP OF THE SCRIPT, BEFORE ANY CODE IS WRITTEN! THE FUNCTION FORCES THE SCRIPT TO RESTART SO PUTTING IT LATER IN THE SCRIPT WILL RE-RUN THE CODE!

 

Example.au3

#Include "_includeDir.au3"
#Include <File.au3> ; Not needed. Just here as an example of a normal script.
#Include <Array.au3> ; Not needed. Just here as example of normal script.
_includeDir("Directory to Include")

MsgBox(0,"Example","This is just an example!")

See how the function is called near the top? This is the proper use of the UDF. If you had a folder called "Directory to Include" and had a bunch of .au3 files inside of it, the function would include them all into the Example.au3 script.

If you run the Example.au3 file now, it will most likely tell you "The directory Things to Include does not exist!". Make sure you enter the name of the directory you're trying to include. Just as a side note, when including files, you should put all of the code in the INCLUDED files inside of functions so they aren't automatically run when included. Variables can be outside of the functions so they are automatically set. Remember, if you have a variable in one included file with the same name of variable in another included file, it will be overwritten with whichever include file was included last.

 

Anyways, if you have pointed the directory to include parameter to a folder that exists and run the Example.au3, it will generate a folder called IncludeDirUDF. It will also write a new line inside of Example.au3. It will write the line 

Quote

#Include "IncludeDirUDF\loadIncludes.au3"

on line one. Of course, you don't always want it to be written to line one, right? Maybe you want this bit of code to be written on line 3 in order to keep your code organize. Is there a way to do this? Absolutely! Simply add the line number as a second parameter to the function. For example, we want to have this bit of code written on line 3, we would set up our Example.au3 file to look like this.

#Include "_includeDir.au3"
#Include <File.au3> ; Not needed. Just here as an example of a normal script.
#Include <Array.au3> ; Not needed. Just here as example of normal script.
_includeDir("Directory to Include", 3)

MsgBox(0,"Example","This is just an example!")

See how we added the 3 to the end of _includeDir? This will tell the function to write the #Include "IncludeDirUDF\loadIncludes.au3" on line 3 of Example.au3. Note, the line HAS TO EXIST in order to be written to it. For example, if your Example.au3 code only has 6 lines, and you specify to be written on line 7, it WILL NOT WORK.

 

The code is designed to include and restart in order to process the included files. For some reason, if you want to JUST generate the included file and NOT restart, you can add one more parameter to the code. If you don't want the code to restart, simply set your code up to look like this:

#Include "_includeDir.au3"
#Include <File.au3> ; Not needed. Just here as an example of a normal script.
#Include <Array.au3> ; Not needed. Just here as example of normal script.
_includeDir("Directory to Include", 3, False)

MsgBox(0,"Example","This is just an example!")

Note, if you set this last parameter to false, it will simply generate the included file and write to line 3 of Example.au3 (As specified before) and exit before the code reaches the MsgBox() and it will not be displayed.

 

The last important thing to note: In order to re-include a different set of files, you must delete the #Include "IncludeDirUDF\loadIncludes.au3" from your main script (In this case, Example.au3) and delete the generated file, IncludeDirUDF. Now you can simply rerun Example.au3 and it will include any the dir with any changes you made to it. Only .au3 files should be in the directory you're trying to include as it will not process the other files and will generate an error.

 

I hope this UDF helps somebody out! Comment any questions/concerns you may have and I will try to address them as soon as possible!

 

Thanks,

Timothy

CEO - Amarok Studios

_includeDir.au3

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

  • Similar Content

    • nacerbaaziz
      By nacerbaaziz
      Hello
      How are you
      I have a question, please.
      I've created a window and i need
      when i run the script if it detect an other copy from the same script was runing
       the script close the first copy Automatically and run a new copy
      I want an example to understand it
    • Nareshm
      By Nareshm
      How to repeat my script when my control class does not match ?
       
      My Script : winActivate ( " PS :: Version - 2.2.0.0  - [PS Bill]")                   ControlClick ( "PS :: Version - 2.2.0.0  - [PS Bill]", "", "[NAME:btnSavebyFP]")                   ControlSend(" PS :: Version - 2.2.0.0  - [PS Bill]", "", "[NAME:btnSavebyFP]", "{enter}")                   WinActive ("Verification Number Entry ::")                   ControlClick("Next >", "","[NAME:btnNext]") ;if   >>>> Control <<<<  does not match repeat my script, ;if match exit script  

      Class:    WindowsForm734a
      Instance:    15
      ClassnameNN:    WindowsForm34a15
      Name:    BillPrint
      Advanced (Class):    [NAME:BillPrint]
      ID:    7875
      Text:    
      Position:    39, 310
      Size:    1221, 306
      ControlClick Coords:    745, 20
      Style:    0x56010000
      ExStyle:    0x00000000
      Handle:    0x00000000000C0468
    • Nareshm
      By Nareshm
      Please Somebody Help me i am trying to create new script but, i don't know how to create it.

      I am Creating script like this :
      ; My script here [First Script]
      Check the internet connection, if internet connected then
      ; My Script here [Second Script]
      If internet not connected, wait for connect, after connected run my second script
      If Control id/windows/title matched do nothing and end/exit autoit script
      If Control id/windows/title not matched repeat my first and second script again until control id/windows/tittle not matched

      match with :
      >>>> Window <<<<
      Title:    PS :: Version - 2.8.0.0  - [PS Bill]
      Class:    WindowsForm734a
      Position:    -8, -8
      Size:    1382, 744
      Style:    0x17CD0000
      ExStyle:    0x00050100
      Handle:    0x0000000000130572
      >>>> Control <<<<
      Class:    WindowsForm734a
      Instance:    15
      ClassnameNN:    WindowsForm34a15
      Name:    BillPrint
      Advanced (Class):    [NAME:BillPrint]
      ID:    7875
      Text:    
      Position:    39, 310
      Size:    1221, 306
      ControlClick Coords:    745, 20
      Style:    0x56010000
      ExStyle:    0x00000000
      Handle:    0x00000000000C0468
       
    • Nareshm
      By Nareshm
      I create message box but i dont know how to add button action when i click it.

      Help for : Add script for Button : Left, Right, Right Finger
      example when i press Left finger button do Case $idNotepad
                      $iPID = WinActivate ( " :PS :: Version - 2.8.0.0  - [eFS Bill]")
                              ControlSend(" :DS  - eF :: Version - 2.8.0.0  - [eF Bill]", "", "[NAME:btnReset]", "{esc}")
                              ControlClick ( " :DS  - eF :: Version - 2.8.0.0  - [eF Bill]", "", "[NAME:txtrdNo]")
                              ControlSend(" :DS  - eF:: Version - 2.8.0.0  - [eF Bill]", "", "[NAME:txtrdNo]", "^v")
                              ControlSend(" :DS  - eF :: Version - 2.8.0.0  - [eF Bill]", "", "[NAME:txtrdNo]", "{enter}")
      How to add like above ?
                    
                                                                sorry for my bad english
       
    • nacerbaaziz
      By nacerbaaziz
      Hi friends, I have a question, please.
      I have created a window containing a edit box
      I need to know how to change the keyboard language,
      e.g :
      if a user open the  script  it will be change the keyBord language   in window automatically into English
      I found more examples but didn't work with me .
      Note:  
       I use the windows 10 os
      Please help me .
      thanks in advance to all
      with my Greetings and my appreciation for all users and admins