Filex.au3

Last modified:   Saturday, 4 April 2009

;*******************************************************************************
;
;   Function List
;         __File_RemoveEmptyLines()
;         __FileReadToArray()
;         __FileWriteFromArray()
;         _File_Compare()
;         _File_CompareDate()
;         _File_CompareVersion()
;         _File_Ext_PropertiesGet()
;         _File_GetDate()
;         _File_GetOwner()
;         _File_MoveByDate()
;         _File_ReadFromLine()
;         _File_SetOwner()
;
;*******************************************************************************

#include-once

;===============================================================================
; Function Name:   __File_Read2Array()
; Description:     Another version of __FileReadToArray() which will also
;                   accept string blocks
; Syntax:          __File_Read2Array("File path | string block")
; Parameter(s):    $sStr = File path or text block to read to the array
; Requirement(s):   
; Return Value(s): 0 based array
; Author(s):   George (GEOSoft) Gedye, Smoke_N
; Modification(s): 
; Note(s):    This can also be used to read the clipboard to an array
; Example(s):   $aArray = __File_Read2Array("c:\windows\setuplog.txt")
;               $aArray = __File_Read2Array(ClipGet())
;===============================================================================

Func __File_Read2Array($sStr)
   If FileExists($sStr) Then $sStr = FileRead($sStr)
   $avArray = StringRegExp($sStr, "(?s)(.+?)(?m:$|\r\n)|(.+?)(?m:$|\r)|(.+?)(?m:$|\n)", 3)
   If NOT IsArray($avArray) Then Return SetError(1, 0, 0)
   Return $avArray
EndFunc   ;<==> __File_Read2Array()

;===============================================================================
; Function Name:    __File_RemoveEmptyLines()
; Description:      Removes Blank lines from a file
; Syntax:           __File_RemoveEmptyLines($sFile[,starting point[, All|double ]])
; Parameter(s):     $sFile - Full path and filename of the file
;                   $iStart - line to start stripping empty lines -default is first line
;                   $all - 0 (default) remove only extra consecutive blank lines
;                        - 1 Remove all blank lines
; Requirements:      None
; Return Value(s):  On Success - Returns the corrected file
;                   On Failure - Sets @Error to
;                                      - 1 if unable to create the array
;                                      - 2 file write operation failed
; Author(s):        George (GEOSoft) Gedye
; Modifications:    Added $all to remove all or extra blanks
;                   Added $iStart - position to start removing empty lines
; Note(s):        
;===============================================================================

Func __File_RemoveEmptyLines($sFile, $iStart = 1, $all = 0)
   Local $aArray = __FileReadToArray($sFile), $I, $sOut = "", $hFile, $fo
   If NOT IsArray($aArray) Then Return SetError(1)
   If $iStart > 1 Then
      For $I = 1 To $iStart
         $sOut &= $aArray[$I] & @CRLF
      Next
   EndIf
   For $I = $iStart To Ubound($aArray)-1
      If $all <> 0 Then
         If StringStripWS($aArray[$I], 8) = "" Then ContinueLoop
      Else
         If StringStripWS($aArray[$I], 8) = "" AND StringStripWS($aArray[$I-1], 8) = "" Then _
               ContinueLoop
      EndIf
      $sOut &= $aArray[$I] & @CRLF
   Next
   FileCopy($sFile, $sFile & ".bak", 1);; for safety
   $hFile = FileOpen($sFile, 2)
   $fo = FileWrite($hFile, StringStripWS($sOut, 2))
   FileClose($hFile)
   If $fo = 0 Then ;; Something went wrong so restore the file
      FileCopy($sFile & ".bak", $sFile, 1)
      SetError(2)
   EndIf
   FileDelete($sFile & ".bak")
EndFunc   ;<==> __File_RemoveEmptyLines()

;===============================================================================
; Function Name:    __FileReadToArray()
; Description:      Reads a text file and returns an array where each element contains a line of text
; Syntax:           _FileReadToArray($sFilePath)
; Parameter(s):     $sFilePath - Path and filename of the file to be read
; Requirements:      None
; Return Value(s):  On Success - Returns an array of the text file
;                   On Failure - Sets @Error to 1 and returns 0
; Author(s):        Jonathan Bennett [jon at hiddensoft dot com]
; Modifications:    GEOSoft 08/01/07 - Removed the $aArray Parameter so it doesnt need to be pre-declared
;                                       Now just call it with $myArray = _FileReadToArray($File)
;                           05/15/08 - Now will split on @CR if @LF not found, as in many html pages.
; Note(s):          None
;===============================================================================

Func __FileReadToArray($sFilePath)
   Local $hFile
   $hFile = FileOpen($sFilePath, 0)
   If $hFile = -1 Then ;; unable to open the file
      SetError(1)
      Return 0
   EndIf
   $aFile = FileRead($hFile, FileGetSize($sFilePath));; Read the file and remove trailing white spaces
   $aFile = StringStripWS($aFile, 2)
   FileClose($hFile)
   If StringInStr($aFile, @LF) Then
      $aArray = StringSplit( StringStripCR($aFile), @LF)
   ElseIf StringInStr($aFile, @CR) Then ;; @LF does not exist so split on the @CR
      $aArray = StringSplit( $aFile, @CR)
   Else ;; unable to split the file
      SetError(1)
      Return 0
   EndIf
   Return $aArray
EndFunc  ;<==> __FileReadToArray()

;===============================================================================
; Function Name:   __FileWriteFromArray
; Description:      Writes Array records to the specified file.
; Syntax:           __FileWriteFromArray($File, $a_Array[, $i_Base = 0[, $i_UBound = 0[, $rEmpty = 0]]])
; Parameter(s):     $File     - String path of the file to write to, or a file handle returned from FileOpen().
;                  $a_Array  - The array to be written to the file.
;                  $i_Base   - Optional: Start Array index to read, normally set to 0 or 1. Default=0
;                  $i_Ubound - Optional: Set to the last record you want to write to the File. default=0 - whole array.
;                  $rEmpty - Optional: Remove blank lines. (default = 0 - No)
; Requirements:      None
; Return Value(s):  Success - Returns a 1
;                  Failure - Returns a 0
;                  @Error  - 0 = No error.
;                  |1 = Error opening specified file
;                  |2 = Input is not an Array
;                  |3 = Error writing to file
; Author(s):        Jos van der Zande <jdeb at autoitscript dot com>
; Modifications:    Updated for file handles by PsaltyDS at the AutoIt forums.
;                   Added ability to skip empty elements when reading from the array. - by GEOSoft.
; Note(s):          If a string path is provided, the file is overwritten and closed.
;                  To use other write modes, like append or Unicode formats, open the file with FileOpen() first
;                     and pass the file handle instead.
;                  If a file handle is passed, the file will still be open after writing.
;===============================================================================

Func __FileWriteFromArray($File, $a_Array, $i_Base = 0, $i_UBound = 0, $rEmpty = 0)
   ; Check if we have a valid array as input
   If Not IsArray($a_Array) Then Return SetError(2, 0, 0)
   If $rEmpty < 0 Then $rEmpty = 0
   
   ; determine last entry
   Local $last = UBound($a_Array) - 1
   If $i_UBound < 1 Or $i_UBound > $last Then $i_UBound = $last
   If $i_Base < 0 Or $i_Base > $last Then $i_Base = 0
   
   ; Open output file for overwrite by default, or use input file handle if passed
   Local $hFile
   If IsString($File) Then
      $hFile = FileOpen($File, 2)
   Else
      $hFile = $File
   EndIf
   If $hFile = -1 Then Return SetError(1, 0, 0)
   
   ; Write array data to file
   Local $ErrorSav = 0
   For $x = $i_Base To $i_UBound
      ; skip empty elements (blank lines) if $rEmpty is not 0
      ;; Remove empty lines if $rEmpty is not 0
      If $rEmpty and StringStripWS($a_Array[$x], 8) = "" Then ContinueLoop
      If FileWrite($hFile, $a_Array[$x] & @CRLF) = 0 Then
         $ErrorSav = 3
         ExitLoop
      EndIf
   Next
   
   ; Close file only if specified by a string path
   If IsString($File) Then FileClose($hFile)
   
   ; Return results
   If $ErrorSav Then
      Return SetError($ErrorSav, 0, 0)
   Else
      Return 1
   EndIf
EndFunc   ;<==> __FileWriteFromArray()

;===============================================================================
; Function Name:    _File_Compare()
; Description:      Performs a string comparison of 2 files
; Syntax:           _File_Compare($sFile_1, $sFile_2, $iWSpace = 0)
; Parameter(s):     $sFile_1 - full path and name of the first file
;                   $sFile_2 - full path and name of the second file
;                   $iWSpace - 0 (default) = do not ignore whitespaces
;                        - anything except 0 = ignore whitespaces
; Requirements:     None
; Return Value(s):  Success = True if the files are identical
;                             False if they are different
;                   Failure - Returns -1 and sets @Error to 1 (invalid file names)
; Author(s):        George (GEOSoft) Gedye
; Modifications:    Now allows you to ignor whitespace differences
; Notes:            The time required to compare depends on the file size and your system
;===============================================================================

Func _File_Compare($sFile_1, $sFile_2, $iWSpace = 0)
   If FileExists($sFile_1) AND FileExists($sFile_2) Then ;; Make sure they are valid file paths
      If $iWSpace = 0 Then
         Return FileRead($sFile_1) = FileRead($sFile_2)
      Else
         Return StringStripWS(FileRead($sFile_1), 8) = StringStripWS(FileRead($sFile_2), 8)
      EndIf
   Else ;; one of the files does not exist
      SetError(1)
      Return -1
   EndIf
EndFunc   ;<===>_File_Compare()

;===============================================================================
; Function Name:    _File_CompareDate()
; Description:      Performs a comparison of 2 file dates
; Syntax:           _File_Compare($s_Vers1, $s_Vers2)
; Parameter(s):     $cFile_1 - full path and name of the first file
;                   $cFile_2 - full path and name of the second file
; Requirements:      None
; Return Value(s):  Success = Returns an array where array[0] = newest file and array[1] = oldest file
;                   Failure - Returns 0 and sets @Error to 1 (invalid file names)
; Author(s):        George (GEOSoft) Gedye
; Modifications:    
; Notes:            
;===============================================================================

Func _File_CompareDate($cFile_1, $cFile_2)
   Local $rVal
   If FileExists($cFile_1) AND FileExists($cFile_2) Then ;; Make sure they are valid file paths
      $dVal_1 = StringTrimRight(FileGetTime($cFile_1, 0, 1), 2) ;; ignore seconds
      $dVal_2 = StringTrimRight(FileGetTime($cFile_2, 0, 1), 2)
      If $dVal_1 - $dVal_2 <= 0 Then
         $nFile = $cFile_2
         $oFile = $cFile_1
      Else
         $nFile = $cFile_1
         $oFile = $cFile_2
      EndIf
      Dim $rtn[2] = [$nFile, $oFile]
      Return $rtn
   Else
      SetError(1)
      Return 0
   EndIf
EndFunc   ;<===>_File_CompareDate()

;===============================================================================
; Function Name:    _File_CompareVersion()
; Description:      Performs an integer comparison of the versions of 2 files
; Syntax:           _File_CompareVersion($s_Vers1, $s_Vers2)
; Parameter(s):     $iFile_1 - full path and name of the first file
;                   $iFile_2 - full path and name of the second file
; Requirements:      None
; Return Value(s):  Success = 1 if $iFile_1 is higher , 2 if $iFile_2 is higher, 0 if they are the same
;                   Failure - Returns -1 and sets @Error to
;                         [1 - if blank values were given for $fVer_1 or $fVer_2
;                         [2 - if the given values were not numeric
; Author(s):        George (GEOSoft) Gedye
; Modifications:    
; Notes:            None
;===============================================================================

Func _File_CompareVersion($iFile_1, $iFile_2)
   Local $v_Rtn
   If $iFile_1 = "" OR $iFile_1 = "" Then ;; blank values are not accepted
      SetError(1)
      Return -1
   EndIf
   $fVer_1 = StringReplace(FileGetVersion($iFile_1), ",", ".")
   $fVer_2 = StringReplace(FileGetVersion($iFile_2), ",", ".")
   $fVer_1 = Number(StringReplace(FileGetVersion($iFile_1), ".", ""))
   $fVer_2 = Number(StringReplace(FileGetVersion($iFile_2), ".", ""))
   If StringLen($fVer_1) <> StringLen($fVer_2) Then
      If StringLen($fVer_1) < StringLen($fVer_2) Then ;; make sure we compare apples with apples
         Do
            $fVer_1 *= 10
         Until StringLen($fVer_1) = StringLen($fVer_2)
      Else
         Do
            $fVer_2 *= 10
         Until StringLen($fVer_1) = StringLen($fVer_2)
      EndIf
   EndIf
   If IsNumber($fVer_1) AND IsNumber($fVer_2) Then
      If $fVer_1 > $fVer_2 Then
         $v_Rtn = 1
      ElseIf $fVer_1 < $fVer_2 Then
         $v_Rtn = 2
      Else
         $v_Rtn = 0
      EndIf
      Return $v_Rtn
   Else
      SetError(2)
      Return -1
   EndIf
EndFunc   ;<===>_File_CompareVersion()

;===============================================================================
; Function Name:    _File_Ext_PropertiesGet()
; Description:      Get the extended properties information of a document, image,
;                    audio or video file
; Syntax:           _File_Ext_PropertiesGet("Full path and file name", "detail" [, $wName])
; Parameter(s):     $sFile - The full path and file name to check
;                   $sDetail - The required extended property (See Notes)
;                   $wName - If not = 0 then the name of the extended property will
;                             be returned in front of the actual value in the form of
;                             "Property : " and then the value of the property
; Requirements:
; Return Value(s):  Success - Returns the extended file property
;                   Failure Sets @Error
;                   [1 - The extended property requested is unknown (check spelling)
;                   [2 - The property requested is not available for the file. Example, trying to check
;                             "Dimensions" of a text document or "Duration" of an image.
;                   [3 - Invalid file path/name
; Author(s):        George (GEOSoft) Gedye
;
; Notes: Valid properties are;
;                     Name, Size, Type, Status, Owner, Author, Title, Subject,
;                     Category, Pages, Comments, Copyright,
;                     Artist, Album Title, Year, Track Number, Genre, Duration,
;                     Bit Rate, Protected, Camera, Date Taken,
;                     Dimensions, Episode, Company, Description, File Version,
;                     Sample Size, Sample Rate, 
;                     Product Name, Product Version, Audio Channels, All
;                     I have left some out that are easier to get using standard 
;                     AutoIt functions, e.g. FileGetAttrib()
;                     If "All" is used then an @CRLF delimited list of all the available
;                      properties (including the property name) is returned.
;
; Modifications: Added a check to see if the file is actaully just a link.
;                Changed the file path method
;                Fixed the return for "All". Now returns only available properties
;===============================================================================

Func _File_Ext_PropertiesGet($sFile, $sDetail, $wName = 0)
   If NOT FileExists($sFile) Then
      If FileExists(FileGetShortName($sFile & ".lnk")) Then
         $sc = FileGetShortcut($sFile)
         $sFile = $sc[0]
      Else
         Return SetError(3, 3, "The file " & FileGetLongName($sFile) & " does not exist")
      EndIf
   EndIf
   $sFile = StringSplit($sFile, "\")
   Local $fName = $sFile[$sFile[0]], $Path = "", $All, $Dtl,  $Rtn = "", $I
   For $I = 1 To $sFile[0]-1
      $Path &= $sFile[$I] & "\"
   Next
   $objShell = ObjCreate("Shell.Application")
   Local $objFolder = $objShell.Namespace(StringTrimRight($Path, 1))
   Switch $sDetail
      Case "Name"
         $Dtl = 0
      Case "Size"
         $Dtl = 1
      Case "Type"
         $Dtl = 2
      Case "Status"
         $Dtl = 7
      Case "Owner"
         $Dtl = 8
      Case "Author"
         $Dtl = 9
      Case "Title"
         $Dtl = 10
      Case "Subject"
         $Dtl = 11
      Case "Category"
         $Dtl = 12
      Case "Pages"
         $Dtl = 13
      Case "Comments"
         $Dtl = 14
      Case "Copyright"
         $Dtl = 15
      Case "Artist"
         $Dtl = 16
      Case "Album Title"
         $Dtl = 17
      Case "Year"
         $Dtl = 18
      Case "Track Number"
         $Dtl = 19
      Case "Genre"
         $Dtl = 20
      Case "Duration"
         $Dtl = 21
      Case "Bit Rate"
         $Dtl = 22
      Case "Protected"
         $Dtl = 23
      Case "Camera"
         $Dtl = 24
      Case "Date Taken"
         $Dtl = 25
      Case "Dimensions"
         $Dtl = 26
      Case "Episode"
         $Dtl = 29
      Case "Company"
         $Dtl = 30
      Case "Description"
         $Dtl = 30
      Case "File Version", "Sample Size"
         $Dtl = 32
      Case "Product Name", "Sample Rate"
         $Dtl = 33
      Case "Product Version", "Audio Channels"
         $Dtl = 34
      Case "All"
         $All = StringSplit("0,1,2,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,29,30,32,33,34", ",")
      Case Else
         Return SetError(1, 1, "Unrecognized property")
   EndSwitch
   If NOT IsArray($All) Then
      For $Filename In $objFolder.Items
         If $objFolder.GetDetailsOf($Filename, 0) = $fName Then
            $Rtn = $objFolder.GetDetailsOf($Filename, $Dtl)
            If $Rtn = "" Then Return SetError(2, 2, "Property " & $objFolder.GetDetailsOf($objFolder.Items, $Dtl) & " is unknown for this file")
            If $wName <> 0 Then $Rtn = $objFolder.GetDetailsOf($objFolder.Items, $Dtl) & " : " & $Rtn
            Return String($Rtn)
         EndIf
      Next
   Else
      For $Filename In $objFolder.Items
         If $objFolder.GetDetailsOf($Filename, 0) = $fName Then
            For $I = 1 TO $All[0]
               If $objFolder.GetDetailsOf($Filename, $All[$i]) = "" Then ContinueLoop
               $Rtn &= $objFolder.GetDetailsOf($objFolder.Items, $All[$i]) & " : " & $objFolder.GetDetailsOf($Filename, $All[$I]) & @CRLF
            Next
         EndIf
      Next
      Return StringStripWS($Rtn, 2)
   EndIf
EndFunc   ;;<==>_File_Ext_PropertiesGet()

;===============================================================================
; Function Name:    _File_GetDate()
; Description:      Reads a text file and returns an array where each element contains a line of text
; Syntax:           _File_GetDate($sFilePath)
; Parameter(s):     $sFilePath - Path and filename of the file to check
; Requirements:      None
; Return Value(s):  On Success - Returns a formatted date string suitable for use with the _Date functions. e.g.
;                                  4 digit year/2 digit month/2 digit day (2008/04/17)
; Author(s):        George (GEOSoft) Gedye
; Modifications:    
; Notes:            None
;===============================================================================

Func _File_GetDate($sFilePath)
   $sFilePath = FileGetShortName($sFilePath)
   $fTime = FileGetTime($sFilePath, 1)
   Return StringFormat("%04d/%02d/%02d", $fTime[0], $fTime[1], $fTime[2])
EndFunc  ;<==> _File_GetDate()

;===============================================================================
; Function Name:   _File_GetOwner()
; Description:   Retrieve the ownership of a file
; Syntax:   _File_GetOwner("FULL path and filename", "computer name")
; Parameter(s):   
; Requirement(s):   
; Return Value(s):   Success - Returns name or group of the file owner
;                    Failure - Returns 0 if file not found (@Error = 0)
;                              Sets @Error to 1 if
;                                   unable to connect to the object
;                                   
; Author(s):   George (GEOSoft) Gedye
; Modification(s):   
; Note(s):   Also works on folders
; Example(s):   
;===============================================================================

Func _File_GetOwner($sFile, $sComputer = "localhost")
   Local $Obj, $Item, $Items, $rVal = ""
   If StringRight($sFile, 1) = "\" Then $sFile = StringTrimRight($sFile, 1)
   $sComputer = StringReplace($sComputer,"\","")
   $Obj = ObjGet("winmgmts:\\" & $sComputer & "\root\cimv2")
   If isObj($Obj) Then
      $Items = $Obj.ExecQuery _
            ("ASSOCIATORS OF {Win32_LogicalFileSecuritySetting='" & $sFile & "'}" & _
            " WHERE AssocClass=Win32_LogicalFileOwner ResultRole=Owner")
      For $Item in $Items
         If $Item.ReferencedDomainName Then
            $rVal = $Item.AccountName
         EndIf
      Next
   Else
      SetError(1)
   EndIf
   Return $rVal
EndFunc  ;<==> _File_GetOwner()

;===============================================================================
; Function Name:   _File_MoveByDate()
; Description:     Use to move or copy files by date created
; Syntax:          _File_MoveByDate($sPath, $sNewPath[, $sPattern = "*"[, $iDate = -1[, $iDateFlag = 1[, $iMove = 1[, $iOverWrite = 1]]]]])
; Parameter(s):    $sPath - the folder to search
;                  $sNewPath - The folder where the files should be moved/copied to
;                  $sPattern - File search pattern.  Default is all
;                  $iDate (optional) - The date to start checking in the format YYYYMMDD. Default is current day
;                  $iDateFlag (optional)- see FileGetTime() for possible values,  Default is 0 (Last Modified)
;                  $iMove (optional) - If not 1 then a copy operation will be performed instead of a move
;                  $iOverWrite (optional) - If 1 (default) then an existing file of the same name will be over-written
;                  $iNewer (optional) - If 1 (default) operation performed on files equal to or newer than $iDate
;                                        else operation performed on files equal to or older than $iDate
; Requirement(s):  
; Return Value(s): - Success - Returns the count of files copied or moved
;                  - Failure - Sets @Error to
;                                   1 - If no files match the pattern
;                                   2 - If the source folder path does not exist
;                                   3 - if unable to create the destination folder
; Author(s):       George (GEOSoft) Gedye
; Modification(s): Added $iNewer parameter (see parameters) 2009/04/04
; Note(s):    
; Example(s):   
#cs
   $sFldr = @ScriptDir & "\"
   $sFldr2 = @DeskTopDir & "\Test Folder\"
   $iMoved = _File_MoveByDate($sFldr, $sFldr2)
   If NOT @Error Then
   MsgBox(0, "Finished", $iMoved & " files were moved or copied")
   If $iMoved Then ShellExecute($sFldr2)
   EndIf
#ce
;===============================================================================

Func _File_MoveByDate($sPath, $sNewPath, $sPattern = "*", $iDate = -1, _
      $iDateFlag = 0, $iMove = 1, $iOverWrite = 1, $iNewer = 1)
   Local $sHold, $aCreated, $iCreated, $iCount = 0, $iValid
   If StringRight($sPath, 1) <> "\" Then $sPath &= "\"
   If NOT FileExists($sPath) Then Return SetError(2)
   If StringRight($sNewPath, 1) <> "\" Then $sNewPath &= "\"
   If $iDateFlag > 2 OR $iDateFlag < 0 Then $iDateFlag = 1
   If NOT FileExists($sNewPath) Then
      If NOT DirCreate($sNewPath) Then Return SetError(3)
   EndIf
   If $iDate = -1 Then $iDate = @Year & @Mon & @mDay
   $sFile = FileFindFirstFile($sPath & $sPattern)
   If NOT @Error Then
      If NOT FileExists($sNewPath) Then DirCreate($sNewPath)
      If $iOverWrite <> 1 Then $iOverWrite = 0
      While 1
         $iValid = False
         $sHold = FileFindNextFile($sFile)
         If @Error Then ExitLoop
         If StringInStr(FileGetAttrib($sPath & $sHold), "D") Then ContinueLoop
         $aCreated = FileGetTime($sPath & $sHold, $iDateFlag)
         $iCreated = $aCreated[0] & $aCreated[1] & $aCreated[2]
         If $iNewer = 1 Then
            If $iCreated >= $iDate Then $iValid = True
         Else
            If $iCreated <= $iDate Then $iValid = True
         EndIf
         If $iValid Then
            If $iMove = 1 Then
               If NOT FileMove($sPath & $sHold, $sNewPath & $sHold, $iOverWrite) Then
                  MsgBox(4096, "File Error", "Unable to Move The File " & $sHold, 5)
                  ContinueLoop
               EndIf
            Else
               If NOT FileCopy($sPath & $sHold, $sNewPath & $sHold, $iOverWrite) Then
                  MsgBox(4096, "File Error", "Unable to Copy The File " & $sHold, 5)
                  ContinueLoop
               EndIf
            EndIf
            $iCount += 1
         EndIf
      Wend
   Else
      Return SetError(1)
   EndIf
   Return $iCount
EndFunc   ;<==> _File_MoveByDate()

;===============================================================================
; Function Name:   _File_ReadFromLine()
; Description:     _File_ReadFromLine($sStr, $iLine)
; Syntax:          
; Parameter(s):    $sStr = a string or the full path to a file to be read
;                  $iLine = Line to begin reading from
; Requirement(s):  
; Return Value(s): - Success The contents starting at the specified line number
;                  - Failure 
; Author(s):       George (GEOSoft) Gedye
; Modification(s): 
; Note(s):    Thanks To SmOke_N for his help on the RegExp
; Example(s):   
#cs
   $String = _File_ReadFromLine("C:\somefile.txt", 8); Will start reading from Line 8
   ClipPut($String)
#ce
;===============================================================================

Func _File_ReadFromLine($sStr, $iLine)
   If $sStr = "" Then Return SetError(1, 0, "")
   If FileExists($sStr) Then $sStr = FileRead($sStr)
   $iLine = Int($iLine)
   If $iLine <= 1 Then Return $sStr
   Local $sRegEx = "(?s)^(.*?(?:\r\n|\r|\n)){" & $iLine & "}(.+?)\z"
   Local $aRegEx = StringRegExp($sStr, $sRegEx, 1)
   If @error Then Return SetError(2, 0, "")
   Return $aRegEx[1]   
EndFunc   ;<==> _File_ReadFromLine()

;===============================================================================
; Function Name:     _File_SetOwner()
; Description:      Set the ownership of a file or folder to the current user
; Syntax:   _File_SetOwner("path & filename" [, "Computer name"[, require admin)
; Parameter(s):   $sFile
;                 $Computer - (optional) name of the computer to run against
;                 $rAdmin - (optional) if 1 then Requires Administrator privledges.
; Requirement(s):
; Return Value(s): Success - returns 0
;                  Failure - returns 1 and sets @Error to 2
;                          - Sets @Error to 1 if $rAdmin = 1 and user is not an admin
; Author(s):   George (GEOSoft) Gedye
; Modification(s):
; Note(s):   If run against a folder then ownership of the files inside will also change
; Example(s):
;===============================================================================

Func _File_SetOwner($sFile, $Computer = "localhost", $rAdmin = 1)
   If $rAdmin > 1 or $rAdmin < 0 Then $rAdmin = 1
   If $rAdmin = 1 AND IsAdmin() = 0 Then Return SetError(1)
   $Computer = StringReplace($Computer, "\", "")
   $obj = ObjGet("winmgmts:\\" & $Computer & "\root\cimv2")
   If IsObj($obj) Then
      $oFile = $obj.Get("CIM_DataFile.Name='" & $sFile & "'")
      $Result = Int($oFile.TakeOwnership)
      Return $Result
   Else
      Return SetError(2)
   EndIf
EndFunc   ;==>_File_SetOwner