Snippets ( Files & Folders )

From AutoIt Wiki
Jump to navigation Jump to search

Please always credit an author in your script if you use their code. It is only polite.


_ConvertFileToUTF16

Author: guinness








_ConvertFileToUTF16(@ScriptDir & "\Example.xml")

Func _ConvertFileToUTF16($sFilePath)
    Local $iEncoding = FileGetEncoding($sFilePath)
    Local $hFileOpen = FileOpen($sFilePath, $iEncoding)
    If $hFileOpen = -1 Then
        Return SetError(1, 0, 0)
    EndIf
    Local $sData = FileRead($hFileOpen)
    FileClose($hFileOpen)

    $hFileOpen = FileOpen($sFilePath, 2 + 32)
    If $hFileOpen = -1 Then
        Return SetError(2, 0, 0)
    EndIf
    FileWrite($hFileOpen, $sData)
    Return FileClose($hFileOpen)
EndFunc   ;==>_ConvertFileToUTF16

ReturnToContents

DropFiles

Author: guinness







Dropping multiple files onto a GUI


; Dropping multiple files onto a GUI

#include <APIConstants.au3>
#include <Array.au3>
#include <GUIConstantsEx.au3>
#include <WinAPIEx.au3>

Global $__aDropFiles

Example()

Func Example()
	Local $hGUI = GUICreate('', 500, 500, -1, -1, -1, $WS_EX_ACCEPTFILES)

	; Create a label that is transparent which will accept 'drop' events.
	GUICtrlCreateLabel("", 0, 0, 500, 500)
	GUICtrlSetBkColor(-1, $GUI_BKCOLOR_TRANSPARENT)
	GUICtrlSetResizing(-1, $GUI_DOCKALL)
	GUICtrlSetState(-1, $GUI_DROPACCEPTED)

	GUIRegisterMsg($WM_DROPFILES, "WM_DROPFILES")
	GUISetState(@SW_SHOW, $hGUI)

	While 1
		Switch GUIGetMsg()
			Case $GUI_EVENT_CLOSE
				ExitLoop

			Case $GUI_EVENT_DROPPED
				If $__aDropFiles[0] > 0 Then
					_ArrayDisplay($__aDropFiles)
				EndIf

		EndSwitch
	WEnd
	GUIDelete($hGUI)
EndFunc   ;==>Example

Func WM_DROPFILES($hWnd, $iMsg, $iwParam, $ilParam)
	#forceref $hWnd, $ilParam
	Switch $iMsg
		Case $WM_DROPFILES
			Local $aReturn = _WinAPI_DragQueryFileEx($iwParam)
			If IsArray($aReturn) Then
				$__aDropFiles = $aReturn
			Else
				Local $aError[1] = [0]
				$__aDropFiles = $aError
			EndIf
	EndSwitch
	Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_DROPFILES

ReturnToContents

_ExitCheckTextChange

Author: NegativeNrG








;Check(when Exit), if Text is not equal to $e_to Then, prompt the user to save or not save.
;_ExitCheckText Change $Edit Handle, $title of messagebox, $message of messagebox, $equal to(default = NULL).

Func _ExitCheckTextChange($E_hnd,$title,$message,$e_to = '')
	Local $buffer, $choice, $filetosave, $handle1
                $buffer = GUIctrlread($E_hnd)
        If $buffer <> $e_to Then
            $choice = Msgbox(4,$title,$message)
            If $choice = 6 Then
                $filetosave = FileSaveDialog('Choose File',@scriptdir,'(*.au3)')
                $handle1 = FileOpen($filetosave,2)
                FileWrite($handle1,$buffer)
                Exit
            Elseif $choice <> 6 Then
            Exit
        EndIf
        Else
        Exit
    EndIf
EndFunc

ReturnToContents

_FileDeleteEx

Author: guinness








; Ref: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365240(v=vs.85).aspx

#include <APIFilesConstants.au3>
#include <WinAPIFiles.au3>

ConsoleWrite(_FileDeleteEx("C:\Example.dat") & @CRLF)

Func _FileDeleteEx($sFilePath)
    Return FileDelete($sFilePath) = 1 ? 1 : Int(_WinAPI_MoveFileEx(FileGetShortName($sFilePath), "", $MOVE_FILE_DELAY_UNTIL_REBOOT))
EndFunc   ;==>_FileDeleteEx

ReturnToContents

_FileCheck

Author: guinness








#include <Date.au3>

; Check if the file was modified less than 24 hours ago.
ConsoleWrite( _FileCheck(@ScriptFullPath, 24) & @CRLF)

Func _FileCheck($sFilePath, $iHours = 24)
    Local $aTime
    If FileExists($sFilePath) = 0 Then
        Return SetError(1, 0, 0)
    EndIf
    $aTime = FileGetTime($sFilePath, 0, 0)
    Return Number(_DateDiff("h", $aTime[0] & "/" & $aTime[1] & "/" & $aTime[2] & " " & $aTime[3] & ":" & $aTime[4] & ":" & $aTime[5], @YEAR & "/" & @MON & "/" & @MDAY & " " & @HOUR & ":" & @MIN & ":" & @SEC) < $iHours)
EndFunc   ;==>_FileCheck

ReturnToContents

_FileCreateEx

Author: guinness








_FileCreateEx(@ScriptDir & '\ExampleFile.txt', 42)

; Create a blank file with a certain size in bytes.
Func _FileCreateEx($sFilePath, $iBytes = 0)
    Return RunWait(@ComSpec & ' /c fsutil file createnew "' & $sFilePath & '" ' & Int($iBytes), @WorkingDir, @SW_HIDE)
EndFunc   ;==>_FileCreateEx

ReturnToContents

_FileID

Author: guinness








#include <Constants.au3>

FileClose(FileOpen(@ScriptDir & '\ExampleFile.txt', 2))
ConsoleWrite(_FileID(@ScriptDir & '\ExampleFile.txt') & @CRLF)
FileDelete(@ScriptDir & '\ExampleFile.txt')

; Rerieve the file id of a filepath.
Func _FileID($sFilePath)
    Local $iPID = Run(@ComSpec & ' /c fsutil file queryfileid "' & $sFilePath & '"', @SystemDir, @SW_HIDE, $STDOUT_CHILD + $STDERR_CHILD), $sReturn = ''
    While 1
        $sReturn &= StdoutRead($iPID)
        If @error Then
            ExitLoop
        EndIf
    WEnd
    Return StringStripWS(StringRegExpReplace($sReturn, 'File\sID\sis\s(.*?)', '$1'), 8)
EndFunc   ;==>_FileID

ReturnToContents

_FileExistsWithQuotes

Author: guinness








ConsoleWrite(_FileExistsWithQuotes('"' & @ScriptDir & '"') & @CRLF)
ConsoleWrite(_FileExistsWithQuotes("'" & @ScriptDir & "'") & @CRLF)
ConsoleWrite(_FileExistsWithQuotes(@ScriptDir) & @CRLF)

; Version: 1.00. AutoIt: V3.3.8.1
; Check a filepath ecists even if the path contains quotation marks.
Func _FileExistsWithQuotes($sFilePath)
    Return FileExists(StringRegExpReplace($sFilePath, '^("|'')*([^"'']+)("|'')*$', '\2'))
EndFunc   ;==>_FileExistsWithQuotes

ReturnToContents

FileLineCount

Author: MKISH







Checks the number of lines in a file (useful for larger files as well)


; Author - MKISH

; Checks the number of lines in a file (useful for larger files as well)

#include <WinAPI.au3>

Local $FILE = "G:\WIN7\sources\boot.wim"
Local $COUNT = 0
Local $start = default
Local $res, $fLen, $err

While 1
	$res = _HexSearch($FILE, StringToBinary("" & @crlf), $start)
	$start = $res + 2
	$COUNT = $COUNT + 1
	If $res = -1 then exitloop
Wend

msgbox(64, "", "Lines count: " & $COUNT)

; _HexSearch function (originally written by Zinthose, modified by MKISH)
Func _HexSearch($FilePath, $BinaryValue, $StartOffset = Default)
        Local $Buffer, $ptr, $hFile, $Result, $Read, $SearchValue, $Pos, $BufferSize = 2048
            If $StartOffset = Default     Then $StartOffset = 0
            If Not FileExists($FilePath)    Then    Return SetError(1, @error, 0)
            $fLen = FileGetSize($FilePath)
            If $StartOffset > $fLen   Then   Return SetError(2, @error, 0)
            If Not IsBinary($BinaryValue)   Then    Return SetError(3, @error, 0)
            If Not IsNumber($StartOffset)   Then    Return SetError(4, @error, 0)
            $SearchValue = BinaryToString($BinaryValue)
            $Buffer = DllStructCreate("byte[" & $BufferSize & "]")
            $ptr = DllStructGetPtr($Buffer)
                $hFile = _WinAPI_CreateFile($FilePath, 2, 2, 1)
                If $hFile = 0 Then Return SetError(5, @error, 0)
            $Result = _WinAPI_SetFilePointer($hFile, $StartOffset)
            $err = @error
            If $Result = 0xFFFFFFFF Then
                _WinAPI_CloseHandle($hFile)
                Return SetError(5, $err, 0)
            EndIf
            $Pos = $StartOffset
            While True
                    $Read = 0
                    $Result = _WinAPI_ReadFile($hFile, $ptr, $BufferSize, $Read)
                    $err = @error
                    If Not $Result Then
                        _WinAPI_CloseHandle($hFile)
                        Return SetError(6, $err, 0)
                    EndIf
                    $Result = DllStructGetData($Buffer, 1)
                    $Result = BinaryToString($Result)
                    $Result = StringInStr($Result, $SearchValue)
                    If $Result > 0 Then ExitLoop
                    If $Read < $BufferSize Then
                        _WinAPI_CloseHandle($hFile)
                        Return -1
                    EndIf
                    $Pos += $Read

            WEnd
            _WinAPI_CloseHandle($hFile)
            If Not $Result Then Return SetError(7, @error, 0)
            $Result = $Pos + $Result - 1
            Return $Result
    EndFunc; ==> _HexSearch

ReturnToContents

_FileOpenDialog

Author: guinness








Local $sFilePath = _FileOpenDialog("", "", "Images (*.jpg;*.bmp)|Videos (*.avi;*.mpg)", Random(1, @DesktopWidth, 1), Random(1, @DesktopHeight, 1), 1 + 4, "")

ConsoleWrite('File = ' & $sFilePath & ', @error = ' & @error & @CRLF)

; #FUNCTION# ====================================================================================================================
; Name ..........: _FileOpenDialog
; Description ...: Initiates a Open File Dialog with the option to set the position of the GUI.
; Syntax ........: _FileOpenDialog($sTitle, $sIntitialDirectory, $sFilter[, $iLeft = -1[, $iTop = -1[, $iOptions = 0[,
;                  $sDefaultName = ""]]]])
; Parameters ....: $sTitle              - Title text of the Dialog GUI.
;                  $sIntitialDirectory  - Initial directory selected in the GUI file tree.
;                  $sFilter             - File type single filter such as "All (*.*)" or "Text files (*.txt)".
;                  $iLeft               - [optional] The left side of the dialog box. By default (-1), the window is centered.
;                  $iTop                - [optional] The top of the dialog box. Default (-1) is centered
;                  $iOptions            - [optional] Dialog Options: To use more than one option, add the required values together. See FileOpenDialog. Default is 0.
;                  $sDefaultName        - [optional] Suggested file name for the user to open. Default is blank ("").
; Return values .: Success: Returns the full path of the file(s) chosen. Results for multiple selections are "Directory|file1|file2|..."
;                  Failure: Sets @error to non-zero.
; Author ........: guinness
; Remarks........: This doesn't change the working directory of the script like FileOpenDialog does.
; Example .......: Yes
; ===============================================================================================================================
Func _FileOpenDialog($sTitle, $sIntitialDirectory, $sFilter, $iLeft = -1, $iTop = -1, $iOptions = 0, $sDefaultName = "")
    Local $hGUI = GUICreate('', -1, -1, $iLeft, $iTop), $sWorkingDir = @WorkingDir
    Local $sFilePath = FileOpenDialog($sTitle, $sIntitialDirectory, $sFilter, $iOptions, $sDefaultName, $hGUI)
    Local $iError = @error
    FileChangeDir($sWorkingDir)
    Return SetError($iError, GUIDelete($hGUI), $sFilePath)
EndFunc   ;==>_FileOpenDialog()

ReturnToContents

_FileRename

Author: JohnOne








;### Rename a file ###
;$sFile = Full path to file
;$sRename = New Filename
;$iOverWrite = 0 or 1

;Success returns 1
;failure, returns 0 and sets @error
; 1 if FileMove fails, 
; 2 if $sFile does not exist
;@extended
; 0 if the new file does not already exist / existed
; 1 if the new file already exists / existed

;#### Example ####
$File = @ScriptDir & '\filetorename.txt'
FileWrite($File, 'Test')
_FileRename($File, 'newname.txt')
If @error Then MsgBox(0, "Error", @error)

Func _FileRename($sFile, $sRename, $iOverWrite = 0)
    Local Const $FILENOTEXIST = 2
    If Not FileExists($sFile) Then Return SetError($FILENOTEXIST, 0, 0)
    Local $_StringLen = StringLen($sFile)
    Local $_StringInStr = StringInStr($sFile, "\", 0, -1, $_StringLen)
    Local $_Count = $_StringLen - $_StringInStr
    Local $_Dir = StringLeft($sFile, $_StringInStr)
    Local $_NewFile = $_Dir & $sRename
    Local $_NewFileExists = FileExists($_NewFile)
    Local $_FileMove = FileMove($sFile, $_NewFile, $iOverWrite)
    Return SetError(Not $_FileMove, $_NewFileExists, $_FileMove)
EndFunc   ;==>_FileRename

_FileRename Alternative

;FileRename(PathFile, RenameFile)
;JohnOne

FileRename(@ScriptDir & "\rename.txt", @ScriptDir & "\renamed.txt")

Func FileRename($FileName, $ReName)

	Local $SHFILEOPSTRUCT, $SourceStruct, $DestStruct
	Local Const $FO_RENAME = 0x0004
	Local Const $FOF_SILENT = 0x0004
	Local Const $FOF_NOCONFIRMATION = 0x0010
	Local Const $FOF_NOERRORUI = 0x0400
	Local Const $FOF_NOCONFIRMMKDIR = 0x0200
	Local Const $NULL = 0

	$SourceStruct = _StringToStruct($FileName)
	$DestStruct = _StringToStruct($ReName)

	$SHFILEOPSTRUCT = DllStructCreate("hwnd hWnd;uint wFunc;ptr pFrom;ptr pTo;int fFlags;int fAnyOperationsAborted;ptr hNameMappings;ptr lpszProgressTitle")

	DllStructSetData($SHFILEOPSTRUCT, "hWnd", $NULL)
	DllStructSetData($SHFILEOPSTRUCT, "wFunc", $FO_RENAME)
	DllStructSetData($SHFILEOPSTRUCT, "pFrom", DllStructGetPtr($SourceStruct))
	DllStructSetData($SHFILEOPSTRUCT, "pTo", DllStructGetPtr($DestStruct))
	DllStructSetData($SHFILEOPSTRUCT, "fFlags", BitOR($FOF_SILENT, $FOF_NOCONFIRMATION, $FOF_NOERRORUI, $FOF_NOCONFIRMMKDIR))
	DllStructSetData($SHFILEOPSTRUCT, "fAnyOperationsAborted", $NULL)
	DllStructSetData($SHFILEOPSTRUCT, "hNameMappings", $NULL)
	DllStructSetData($SHFILEOPSTRUCT, "lpszProgressTitle", $NULL)

	$acall = DllCall("shell32.dll", "int", "SHFileOperation", "ptr", DllStructGetPtr($SHFILEOPSTRUCT))
	If @error Then
		Return SetError(@error, @extended, 0)
	EndIf
	Return 1
EndFunc   ;==>FileRename

Func _StringToStruct($string)

	Local $iLen = StringLen($string)
	Local $Struct = DllStructCreate("char[" & String($iLen + 2) & "]")
	DllStructSetData($Struct, 1, $string)
	DllStructSetData($Struct, 1, 0, $iLen + 1)
	DllStructSetData($Struct, 1, 0, $iLen + 2)

	Return $Struct
EndFunc   ;==>_StringToStruct

ReturnToContents

_GetFolderDepth

Author: guinness








; Autoit 3.3.5.4 and Below
ConsoleWrite(_GetFolderDepth(@ScriptDir & '') & @CRLF)
ConsoleWrite(_GetFolderDepth(@ScriptDir) & @CRLF)
ConsoleWrite(_GetFolderDepth(@ScriptFullPath) & @CRLF)

; Get the folder depth of a filepath.
Func _GetFolderDepth($sFilePath)
    If StringInStr($sFilePath, '.', 2, -1) Then
        $sFilePath = StringLeft($sFilePath, StringInStr($sFilePath, "", 2, -1) - 1)
    EndIf
    Local $aArray = StringSplit(StringRegExpReplace($sFilePath, '[/]+z', ''), '')
    Return $aArray[0] - 1
EndFunc   ;==>_GetFolderDepth

ReturnToContents

_GetFolderDepth

Author: guinness








; Autoit 3.3.5.4 and Above
ConsoleWrite(_GetFolderDepth(@ScriptDir & '') & @CRLF)
ConsoleWrite(_GetFolderDepth(@ScriptDir) & @CRLF)
ConsoleWrite(_GetFolderDepth(@ScriptFullPath) & @CRLF)

; Get the folder depth of a filepath. Works with V3.3.5.4+
Func _GetFolderDepth($sFilePath)
    If StringInStr($sFilePath, '.', 2, -1) Then
        $sFilePath = StringLeft($sFilePath, StringInStr($sFilePath, "", 2, -1) - 1)
    EndIf
    Return StringSplit(StringRegExpReplace($sFilePath, '[/]+z', ''), '')[0] - 1
EndFunc   ;==>_GetFolderDepth

ReturnToContents

_IsDir

Author: guinness








ConsoleWrite("IsDir: Using a file - " & IsDir(@ScriptFullPath) & @CRLF) ; Return 0
ConsoleWrite("IsDir: Using a directory - " & IsDir(@ScriptDir) & @CRLF) ; Return 1

Func IsDir($sFilePath)
	Return Int(FileExists($sFilePath) And StringInStr(FileGetAttrib($sFilePath), 'D', Default, 1) > 0)
EndFunc   ;==>IsDir

ReturnToContents

_IsFile

Author: guinness








ConsoleWrite('IsFile: Using a file - ' & IsFile(@ScriptFullPath) & @CRLF) ; Return 1
ConsoleWrite('IsFile: Using a directory - ' & IsFile(@ScriptDir) & @CRLF) ; Return 0

Func IsFile($sFilePath)
	Return Int(FileExists($sFilePath) And StringInStr(FileGetAttrib($sFilePath), 'D', Default, 1) = 0)
EndFunc   ;==>IsFilee

ReturnToContents

_IsFileDiff

Author: guinness








ConsoleWrite(_IsFileDiff(@ScriptFullPath, @ScriptFullPath) & @CRLF) ; This will return False as the files are exactly the same.
ConsoleWrite(_IsFileDiff(@ScriptFullPath, @AutoItExe) & @CRLF) ; This will return True as the files are different.

; Check if a file is different.
Func _IsFileDiff($sFilePath_1, $sFilePath_2)
    Return RunWait(@ComSpec & ' /c FC /B /W "' & $sFilePath_1 & '" "' & $sFilePath_2 & '"', @WorkingDir, @SW_HIDE) > 0
EndFunc   ;==>_IsFileDiff

ReturnToContents

_IsFileOlder

Author: guinness








#include <Date.au3> ; Required for _DateDiff()
#include <MsgBoxConstants.au3>
#include <MsgBoxConstants.au3>

; Check if the current script is older than 10 days.
If _IsFileOlder(@ScriptFullPath, 10) Then
	MsgBox($MB_SYSTEMMODAL, '', 'File is older than 10 days.')
Else
	MsgBox($MB_SYSTEMMODAL, '', 'File isn''t older than 10 days.')
EndIf

; Is a file older than a certain number of days.
Func _IsFileOlder($sFilePath, $iDays)
	Local $aArray = FileGetTime($sFilePath, $FT_CREATED)
	Return _DateDiff('D', $aArray[0] & '/' & $aArray[1] & '/' & $aArray[2] & ' ' & $aArray[3] & ':' & $aArray[4] & ':' & $aArray[5], @YEAR & '/' & @MON & '/' & @MDAY & ' ' & @HOUR & ':' & @MIN & ':' & @SEC) >= $iDays
EndFunc   ;==>_IsFileOlder

ReturnToContents

_IsFileSame

Author: guinness








ConsoleWrite(_IsFileSame(@ScriptFullPath, @ScriptFullPath) & @CRLF) ; This will return True as the files are exactly the same.
ConsoleWrite(_IsFileSame(@ScriptFullPath, @AutoItExe) & @CRLF) ; This will return False as the files are different.

; Check if a file is the same.
Func _IsFileSame($sFilePath_1, $sFilePath_2)
    Return RunWait(@ComSpec & ' /c FC /B /W "' & $sFilePath_1 & '" "' & $sFilePath_2 & '"', @WorkingDir, @SW_HIDE) = 0
EndFunc   ;==>_IsFileSame

ReturnToContents

_IniReadFile

Author: guinness








#include <Array.au3>

__INIFileFill(@ScriptDir & '\Example.ini') ; Create an INI file with random data.

Local $aArray = _IniReadFile(@ScriptDir & '\Example.ini')
FileDelete(@ScriptDir & '\Example.ini')
_ArrayDisplay($aArray)

Func _IniReadFile($sFilePath)
    Local $aReturn[1][3] = [[0, 3]], $aSectionArray, $aSectionNameArray, $iCount = 0
    $aSectionNameArray = IniReadSectionNames($sFilePath)
    If @error Then
        Return SetError(1, 0, $aReturn)
    EndIf
    For $A = 1 To $aSectionNameArray[0]
        $aSectionArray = IniReadSection($sFilePath, $aSectionNameArray[$A])
        If @error Then
            ContinueLoop
        EndIf
        For $B = 1 To $aSectionArray[0][0]
            $aReturn[0][0] += 1
            $iCount += 1
            If $aReturn[0][0] <= $iCount + 1 Then
                ReDim $aReturn[$aReturn[0][0] * 2][$aReturn[0][1]]
            EndIf
            $aReturn[$iCount][0] = $aSectionArray[$B][0]
            $aReturn[$iCount][1] = $aSectionArray[$B][1]
            $aReturn[$iCount][2] = $aSectionNameArray[$A]
        Next
    Next
    ReDim $aReturn[$aReturn[0][0] + 1][$aReturn[0][1]] ; Remove empty entries.
    Return $aReturn
EndFunc   ;==>_IniReadFile

Func __INIFileFill($sFilePath)
    Local $sData = '', $sHeader = ''

    For $i = 1 To Random(1, 5, 1)
        $sHeader = _RandomText(Random(5, 25, 1))
        $sData = ""
        For $j = 1 To Random(1, 25, 1)
            $sData &= _RandomText(Random(5, 25, 1)) & '=' & _RandomText(Random(5, 25, 1)) & @LF
        Next
        IniWriteSection($sFilePath, $sHeader, $sData)
    Next
EndFunc   ;==>__FillINIFile

Func _RandomText($iLength = 10)
    Local $sData = '', $sRandom = ''
    For $i = 1 To $iLength
        $sRandom = Random(55, 116, 1)
        $sData &= Chr($sRandom + 6 * ($sRandom > 90) - 7 * ($sRandom < 65))
    Next
    Return $sData
EndFunc   ;==>_RandomText

ReturnToContents

_IniReadInit

Author: mlowery








;===============================================================================
; Description:     Reads values from INI or creates INI with initial values.
;                  Intended to ensure all available INI settings are exposed
;                  and editable.
;                  Parameters are identical to IniRead()
; Parameter(s):    $filename  = filename of INI
;                  $section  = section name of INI
;                  $key      = key name in section
;                  $default  = default value (written to INI if not exists)
; Requirement(s):  None
; Return Value(s): Returns value from INI (or default if not defined)
; Note(s):         Chr(127) used to detect non-existing value since won't normally exist in a text file
;===============================================================================
Func _IniReadInit($filename, $section, $key, $default)
  Local $value = IniRead($filename, $section, $key, Chr(127))
    If $value = Chr(127) Then
      IniWrite($filename, $section, $key, $default)
      $value = $default
    EndIf
    Return $value
EndFunc

ReturnToContents

_IsValidFileType

Author: guinness








ConsoleWrite(@ScriptFullPath & " >> " & _IsValidFileType(@ScriptFullPath, "bat;cmd;au3") & @CRLF)
ConsoleWrite(@AutoItExe & " >> " & _IsValidFileType(@AutoItExe, "bat;cmd;au3") & @CRLF)

; Check if a filepath matches an extension filetype. Based on the idea by guinness - http://www.autoitscript.com/forum/topic/123674-isvalidfiletype/
Func _IsValidFileType($sFilePath, $sList = "bat;cmd;exe") ; By AZJIO - http://www.autoitscript.com/forum/topic/...filetype/page__view__findpost_
    Local $iDot = StringInStr($sFilePath, ".", 0, -1)
    Return $iDot And StringInStr(';' & $sList & ';', ';' & StringTrimLeft($sFilePath, $iDot) & ';') > 0
EndFunc   ;==>_IsValidFileType
; Example 2

#include <WinAPIEx.au3>

ConsoleWrite(@ScriptFullPath & " >> " & _IsValidFileType(@ScriptFullPath, "bat;cmd;au3") & @CRLF)
ConsoleWrite(@AutoItExe & " >> " & _IsValidFileType(@AutoItExe, "bat;cmd;au3") & @CRLF)

; Check if a filepath matches an extension filetype. Based on the idea by guinness - http://www.autoitscript.com/forum/topic/123674-isvalidfiletype/
Func _IsValidFileType($sFilePath, $sList = "bat;cmd;exe", $iOpFast = 1) ; By Yashied.
    If StringStripWS($sList, 8) = "" Then
        $sList = "*"
    EndIf
    Return _WinAPI_PathMatchSpec($sFilePath, StringReplace(';' & $sList, ';', ';*.', 0, $iOpFast * 2))
EndFunc   ;==>_IsValidFileType

ReturnToContents

File Open/Save/Folder Dialog Box

Author: MHz

Author: odklizec

Author: Danny35d






; Center - File Open/Save/Folder Dialog Box
; Author - odklizec, MHz, Danny35d

 If StringInStr($cmdlineraw, '/MoveWin') Then
	 Local $size, $PosX, $PosY
     $cmdlineraw = StringSplit(StringMid($cmdlineraw, StringInStr($cmdlineraw, '/MoveWin')), ':')
     While 1
         Select
         Case WinExists($cmdlineraw[2])
             $size=WinGetPos ($cmdlineraw[2])
             $PosX=@DesktopWidth/2 - $size[2]/2
             $PosY=@DesktopHeight/2 - $size[3]/2
             WinMove($cmdlineraw[2], "", $PosX, $PosY)
             WinActivate($cmdlineraw[2])
             ExitLoop
         EndSelect
         Sleep(50)
     WEnd
     Exit
 EndIf
Global $PID, $Read_File, $Save_File
 $PID = _FindBrowseWin('Open file Dialog Box')
 $Read_File = FileOpenDialog ( "Open file Dialog Box", @ScriptDir & "\", "AutoIt Files (*.au3)",3,@ScriptFullPath)
 ProcessClose($PID)
 $PID = _FindBrowseWin('Save file Dialog Box')
 $Save_File = FileSaveDialog( "Save file Dialog Box", @ScriptDir, "Scripts (*.aut;*.au3)", 3)
 ProcessClose($PID)
 $PID = _FindBrowseWin('Browse for Folder')
 FileSelectFolder("Choose a folder with plugins..", "","4","c:\")
 ProcessClose($PID)

 Func _FindBrowseWin($sTitle)
     If @Compiled Then
         Return(Run(@ScriptFullPath & ' /MoveWin:' & $sTitle))
     Else
         Return(Run(@AutoItExe & ' "' & @ScriptFullPath & '" /MoveWin:' & $sTitle))
     EndIf
 EndFunc

ReturnToContents

_MoveFileOnReboot

Author: JScript








;Author: JScript - Snippet Version No. = 1.0
;Snippet was Created Using AutoIt Version = 3.3.2.0, Creation Date = 21/03/12.

; Function to Move or Delete a file on next reboot!
Func _MoveFileOnReboot($sSourcePath, $sDestPath = ""); If $sDestPath = "" the file is deleted instead of moved.
    Local $iRet

    ; PendingFileRenameOperations (HKLM\SYSTEM\CurrentControlSet\Control\Session Manager)
    If $DestPath = "" Then
        $iRet = DllCall("kernel32.dll", "int", "MoveFileExA", "str", $sSourcePath, "int", 0, "dword", 4)
    Else
        $iRet = DllCall("kernel32.dll", "int", "MoveFileExA", "str", $sSourcePath, "str", $sDestPath, "dword", 4)
    EndIf

    Return $iRet
EndFunc   ;==>_MoveFileOnReboot

ReturnToContents

_MultipleFileOpenDialog

/dev/null








Local $message = "Hold down Ctrl or Shift to choose multiple files."

Local $filename = _MultipleFileOpenDialog($message,300,300)

Local $var = FileOpenDialog($message, @WindowsDir & "\", "Images (*.jpg;*.bmp)", 1 + 4 )

If @error Then
    MsgBox(4096,"","No File(s) chosen")
Else
    $var = StringReplace($var, "|", @CRLF)
    MsgBox(4096,"","You chose " & $var)
EndIf

FileDelete($filename)
func _MultipleFileOpenDialog($title,$posx,$posy)
    Local $temp = EnvGet("temp")
    Local $filename = $temp & "\move_file_open_dialog.au3"

    Local $script = 'Global $title = "' & $title & '"' & @CRLF
    $script &= 'Global $pos_x = ' & $posx & @CRLF
    $script &= 'Global $pos_y = ' & $posy & @CRLF
    $script &= 'AdlibRegister("_Move",10)' & @CRLF
    $script &= 'while 1' & @CRLF
    $script &= '    sleep(1000)' & @CRLF
    $script &= 'wend' & @CRLF
    $script &= 'Func _Move()' & @CRLF
    $script &= '   if (WinActive($title)) Then' & @CRLF
    $script &= '      WinMove($title,"",$pos_x,$pos_y)' & @CRLF
    $script &= '      Exit' & @CRLF
    $script &= '   EndIf' & @CRLF
    $script &= 'EndFunc' & @CRLF

    FileWrite($filename,$script)
    ;MsgBox(0,"",$script & @CRLF & $filename)
    Run(@AutoItExe & " /AutoIt3ExecuteScript " & $filename)
    sleep(250)
    Return $filename
EndFunc ;==>_MultipleFileOpenDialog()

ReturnToContents

_OpenFolder

Author: guinness








#cs
    These have been declared in Global scope as you may wish to use them elsewhere in your script.
#ce
Global $ALTSTARTUP = 0x1d
Global $APPDATA = 0x1a
Global $BITBUCKET = 0x0a
Global $COMMONALTSTARTUP = 0x1e
Global $COMMONAPPDATA = 0x23
Global $COMMONDESKTOPDIR = 0x19
Global $COMMONFAVORITES = 0x1f
Global $COMMONPROGRAMS = 0x17
Global $COMMONSTARTMENU = 0x16
Global $COMMONSTARTUP = 0x18
Global $CONTROLS = 0x03
Global $COOKIES = 0x21
Global $DESKTOP = 0x00
Global $DESKTOPDIRECTORY = 0x10
Global $DRIVES = 0x11
Global $FAVORITES = 0x06
Global $FONTS = 0x14
Global $HISTORY = 0x22
Global $INTERNETCACHE = 0x20
Global $LOCALAPPDATA = 0x1c
Global $MYPICTURES = 0x27
Global $NETHOOD = 0x13
Global $NETWORK = 0x12
Global $PERSONAL = 0x05
Global $PRINTERS = 0x04
Global $PRINTHOOD = 0x1b
Global $PROFILE = 0x28
Global $PROGRAMFILES = 0x26
Global $PROGRAMFILESx86 = 0x30
Global $PROGRAMS = 0x02
Global $RECENT = 0x08
Global $SENDTO = 0x09
Global $STARTMENU = 0x0b
Global $STARTUP = 0x07
Global $SYSTEM = 0x25
Global $SYSTEMx86 = 0x29
Global $TEMPLATES = 0x15
Global $WINDOWS = 0x24

ConsoleWrite(_OpenFolder(@ScriptDir) & @CRLF)
ConsoleWrite(_OpenFolder($PRINTERS) & @CRLF)

; Open a folder or special folder variable, similar to using ShellExecute.
Func _OpenFolder($sFolderPath)
    Local $oShell = ObjCreate('shell.application')
    If @error Then
        Return SetError(1, 0, 0)
    EndIf
    $oShell.Open($sFolderPath)
    Return 1
EndFunc   ;==>_OpenFolder

ReturnToContents

_PathAppendToFilename

Author: ProgAndy








$sOrg = "C:\Some.Folder\some.file.ext"
$sAdd = "_backup"

$sNew = _PathAppendToFilename($sOrg, $sAdd)

$sStripped = _PathStripRightFromFilename($sNew, $sAdd)

MsgBox(0, "", $sOrg & @CRLF & $sAdd & @CRLF & $sNew & @CRLF & $sStripped)

Func _PathAppendToFilename($sName, $sAppend)
    ; Author: ProgAndy
    If StringRegExp($sAppend, '[\/\\:\?"<>\|\*]') Then Return SetError(1, 0, $sName)
    Return StringRegExpReplace($sName, "(\.[^\\/\.]+)$", $sAppend & "\1", 1)
EndFunc

ReturnToContents

_PathStripRightFromFilename

Author: ProgAndy








Func _PathStripRightFromFilename($sName, $sStrip)
    ; Author: ProgAndy
    If StringRegExp($sStrip, '[\/\\:\?"<>\|\*]') Then Return SetError(1, 0, $sName)
    Return StringRegExpReplace($sName, "\Q" & $sStrip & "\E(\.[^\\/\.]+)$", "\1", 1)
EndFunc

ReturnToContents

_SelfDelete

Author: MHz








; This also removes the directory which the file is in
; Author MHz with the directory delete addition by The Kandie Man
Func _SelfDelete($iDelay = 0)
    Local $sCmdFile
    FileDelete(@TempDir & "\scratch.bat")
    $sCmdFile = 'ping -n ' & $iDelay & '127.0.0.1 > nul' & @CRLF _
            & ':loop' & @CRLF _
            & 'del "' & @ScriptFullPath & '"' & @CRLF _
            & 'if exist "' & @ScriptFullPath & '" goto loop' & @CRLF _
            & ':loop2' & @CRLF _
            & 'rmdir /q "' & $dirToDelete & '"' & @CRLF _
            & 'if exist "' & $dirToDelete & '" goto loop2' & @CRLF _
            & 'del ' & @TempDir & '\scratch.bat'
    FileWrite(@TempDir & "\scratch.bat", $sCmdFile)
    Run(@TempDir & "\scratch.bat", @TempDir, @SW_HIDE)
EndFunc

ReturnToContents

_ShellExecuteFileSelectFolder

Author: guinness








ConsoleWrite(_ShellExecuteFileSelectFolder('Select a Folder', @HomeDrive) & @CRLF)

; Shell Execute a selected folder.
Func _ShellExecuteFileSelectFolder($sText, $sRoot, $iFlag = 0, $sInitialDir = '', $hWnd = '')
    Local $sFolder = FileSelectFolder($sText, $sRoot, $iFlag, $sInitialDir, $hWnd)
    If @error Then
        Return SetError(@error, @extended, '')
    EndIf
    ShellExecute($sFolder)
    Return $sFolder
EndFunc   ;==>_ShellExecuteFileSelectFolder

ReturnToContents

_SuiCide

Author: LarryDalooza








; IMPORTANT MAKE A COPY OF SCRIPT BEFORE DELETION
; Deletes the running script

Func SuiCide()
	Local $sFilePath = @TempDir & '\SuiCide.bat'
	FileDelete($sFilePath)
	FileWrite($sFilePath, 'loop:' & @CRLF & 'del "' & @ScriptFullPath & '"' & @CRLF & _
			'ping -n 1 -w 250 zxywqxz_q' & @CRLF & 'if exist "' & @ScriptFullPath & _
			'" goto loop' & @CRLF & 'del SuiCide.bat' & @CRLF)
	Exit Run($sFilePath, @TempDir, @SW_HIDE)
EndFunc   ;==>SuiCide

ReturnToContents

_UniqueFilename

Author: guinness








ConsoleWrite(_UniqueFilename(@ScriptDir, '.au3') & @CRLF)

Func _UniqueFilename($sFilePath, $sExtension)
    Local $iRandom = 0, $sUnqiueFileName = ''

    $sExtension = '.' & StringRegExpReplace($sExtension, '\A[\.]+', '')
    $sFilePath = StringRegExpReplace($sFilePath, '[\\/]+\z', '') & '\'
    While 1
        $iRandom = Random(55, 116, 1)
        $sUnqiueFileName &= Chr($iRandom + 6 * ($iRandom > 90) - 7 * ($iRandom < 65))
        If FileExists($sFilePath & $sUnqiueFileName & $sExtension) = 0 And StringLen($sUnqiueFileName) > 7 Then
            ExitLoop
        EndIf
    WEnd
    Return $sFilePath & $sUnqiueFileName & $sExtension
EndFunc   ;==>_UniqueFilename

ReturnToContents

Windows - Copy With Progress

Author: Jos








; Windows - Copy With Progress

;~ 4 Do not display a progress dialog box.
;~ 8 Give the file being operated on a new name in a move, copy, or rename operation if a file with the target name already exists.
;~ 16 Respond with "Yes to All" for any dialog box that is displayed.
;~ 64 Preserve undo information, if possible.
;~ 128 Perform the operation on files only if a wildcard file name (*.*) is specified.
;~ 256 Display a progress dialog box but do not show the file names.
;~ 512 Do not confirm the creation of a new directory if the operation requires one to be created.
;~ 1024 Do not display a user interface if an error occurs.
;~ 2048 Version 4.71. Do not copy the security attributes of the file.
;~ 4096 Only operate in the local directory. Don't operate recursively into subdirectories.
;~ 8192 Version 5.0. Do not copy connected files as a group. Only copy the specified files.

_FileCopy("C:\Installed Apps\Patches\WindowsXP-KB835935-SP2-ENU.exe","C:\temp")

; to copy a directory the destination directory must exist

Func _FileCopy($fromFile,$tofile)
    Local $FOF_RESPOND_YES = 16
    Local $FOF_SIMPLEPROGRESS = 256
    $winShell = ObjCreate("shell.application")
    $winShell.namespace($tofile).CopyHere($fromFile,$FOF_RESPOND_YES)
EndFunc


Windows - Built In ZIP and Unzip (Windows Shell)

Nine








#include <Constants.au3>
#include <String.au3>

Opt("MustDeclareVars", 1)

Const $sZipFile = @ScriptDir & "\Test.zip"
Const $sFolder = @ScriptDir & "\Temp"
Const $sZipNew = @ScriptDir & "\Test2.zip"

DirRemove ($sFolder, $DIR_REMOVE)
UnZip($sZipFile, $sFolder)
If @error Then Exit MsgBox ($MB_SYSTEMMODAL,"","Error unzipping files : " & @error)
FileDelete ($sZipNew)
Zip ($sZipNew, $sFolder)
If @error Then Exit MsgBox ($MB_SYSTEMMODAL,"","Error zipping files : " & @error)

Func UnZip($sZipFile, $sDestFolder)
  If Not FileExists($sZipFile) Then Return SetError (1) ; source file does not exists
  If Not FileExists($sDestFolder) Then
    If Not DirCreate($sDestFolder) Then Return SetError (2) ; unable to create destination
  Else
    If Not StringInStr(FileGetAttrib($sDestFolder), "D") Then Return SetError (3) ; destination not folder
  EndIf
  Local $oShell = ObjCreate("shell.application")
  Local $oZip = $oShell.NameSpace($sZipFile)
  Local $iZipFileCount = $oZip.items.Count
  If Not $iZipFileCount Then Return SetError (4) ; zip file empty
  For $oFile In $oZip.items
    $oShell.NameSpace($sDestFolder).copyhere($ofile)
  Next
EndFunc   ;==>UnZip

Func Zip ($sZipFile, $sSourceFolder)
  If FileExists($sZipFile) Then Return SetError (1) ; destination file already exists
  If Not FileExists($sSourceFolder) Then Return SetError (2) ; source does not exist
  Local $hFile = FileOpen ($sZipFile, $FO_CREATEPATH+$FO_OVERWRITE+$FO_BINARY)
  Local Const $sString = Chr(80) & Chr(75) & Chr(5) & Chr(6) & _StringRepeat (Chr(0), 18) ; create ZIP file signature
  FileWrite ($hFile, $sString)
  FileClose($hFile)
  Local $oShell = ObjCreate("shell.application")
  If Not $oShell.NameSpace ($sSourceFolder).items.count Then Return SetError (3) ; folder empty
  Local $iFiles = 0
  For $oFile In $oShell.NameSpace($sSourceFolder).items
    $oShell.NameSpace($sZipFile).copyhere($oFile)
    Do
      Sleep (100) ; let the file being copied to ZIP
    Until $oShell.NameSpace($sZipFile).items.count > $iFiles
    $iFiles = $oShell.NameSpace($sZipFile).items.count
  Next
EndFunc


ReturnToContents