Jump to content

_PathFull()/_PathGetRelative() and _PathSplit() created using the functions from WinAPIEx.au3


guinness
 Share

Recommended Posts

This post is not a request to change the following functions in the File.au3 UDF but about looking at an alternative route to getting the same results of the respective functions.

As the idiom says "There's more than one way to skin a cat."

Note: For these functions to work correctly you will require to be added to either the Include folder located in the install path of AutoIt or the location of where you save these functions.

Even though some of these examples aren't 'speedy' I decided to create them anyway to showcase that the Windows API has a lot to offer when creating an application or code. In the past I've found that after creating a convoluted function that a simple API call would've been suffice.

My gratitude goes towards Yashied as well as the author(s) of the original functions (in File.au3) as without the initial idea(s) I wouldn't have created these functions.

Any comments or suggestions then please post below. Thanks.

Example use of _PathSplitEx:

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7
#include <Array.au3>
#include <File.au3>
#include <WinAPIEx.au3>  ; Download From http://www.autoitscript.com/forum/topic/98712-winapiex-udf/ by Yashied.

Local $aArray = 0, $hTimer = 0, $sDirectory = '', $sDrive = '', $sExtension = '', $sFileName = '' ; Variables to be used with _PathSplit() & _PathSplitEx()

$hTimer = TimerInit()
$aArray = _PathSplit(@ScriptFullPath, $sDrive, $sDirectory, $sFileName, $sExtension)
$hTimer = TimerDiff($hTimer)
ConsoleWrite('Orignal:             ' & @ScriptFullPath & @CRLF & _
        'Drive:               ' & $sDrive & @CRLF & _
        'Directory:           ' & $sDirectory & @CRLF & _
        'FileName:            ' & $sFileName & @CRLF & _
        'Extension:           ' & $sExtension & @CRLF & _
        '_PathSplit Time:     ' & $hTimer & @CRLF & @CRLF)
_ArrayDisplay($aArray, '_PathSplit in AutoIt')

$hTimer = TimerInit()
$aArray = _PathSplitEx(@ScriptFullPath, $sDrive, $sDirectory, $sFileName, $sExtension)
$hTimer = TimerDiff($hTimer)
ConsoleWrite('Orignal:             ' & @ScriptFullPath & @CRLF & _
        'Drive:               ' & $sDrive & @CRLF & _
        'Directory:           ' & $sDirectory & @CRLF & _
        'FileName:            ' & $sFileName & @CRLF & _
        'Extension:           ' & $sExtension & @CRLF & _
        '_PathSplitEx() Time: ' & $hTimer & @CRLF & @CRLF)
_ArrayDisplay($aArray, '_PathSplitEx by guinness')

Func _PathSplitEx($sFilePath, ByRef $sDrive, ByRef $sDirectory, ByRef $sFileName, ByRef $sExtension) ; Created by guinness with the idea from _PathSplit().
    Local $aReturn[5] = [$sFilePath, _
            StringTrimRight(_WinAPI_PathStripToRoot($sFilePath), 1), _ ; Required to mimic the return style of _PathSplit(). _WinAPI_PathRemoveBackslash() doesn't work on the drive path.
            '' & _WinAPI_PathSkipRoot(_WinAPI_PathRemoveFileSpec($sFilePath)) & '', _ ;  are required to mimic the return style of _PathSplit().
            _WinAPI_PathStripPath(_WinAPI_PathRemoveExtension($sFilePath)), _
            _WinAPI_PathFindExtension($sFilePath)]
    $sDrive = $aReturn[1]
    $sDirectory = $aReturn[2]
    $sFileName = $aReturn[3]
    $sExtension = $aReturn[4]
    Return $aReturn
EndFunc   ;==>_PathSplitEx

Example use of _PathGetRelativeEx:

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7
#include <File.au3>
#include <WinAPIEx.au3>  ; Download From http://www.autoitscript.com/forum/topic/98712-winapiex-udf/ by Yashied.

Local $hTimer = 0, $sFilePath = ''

$hTimer = TimerInit()
$sFilePath = _PathGetRelative(@ScriptDir, @ScriptFullPath)
$hTimer = TimerDiff($hTimer)
ConsoleWrite('Original Path:             ' & @ScriptFullPath & @CRLF & _
        'Relative Path:             ' & $sFilePath & @CRLF & _
        '_PathGetRelative() Time:   ' & $hTimer & @CRLF & @CRLF)

$hTimer = TimerInit()
$sFilePath = _PathGetRelativeEx(@ScriptDir, @ScriptFullPath)
$hTimer = TimerDiff($hTimer)
ConsoleWrite('Original Path:             ' & @ScriptFullPath & @CRLF & _
        'Relative Path:             ' & $sFilePath & @CRLF & _
        '_PathGetRelativeEx() Time: ' & $hTimer & @CRLF & @CRLF)

Func _PathGetRelativeEx($sFrom, $sTo) ; Created by guinness with the idea from _PathGetRelative().
    Local $iIsFolder = 0
    If _WinAPI_PathIsDirectory($sTo) Then ; Check the destination path is a directory or file path.
        $sTo = _WinAPI_PathAddBackslash($sTo) ; Add a backslash to the directory.
        $iIsFolder = 1
    EndIf
    Local $sRelativePath = _WinAPI_PathRelativePathTo(_WinAPI_PathAddBackslash($sFrom), 1, $sTo, $iIsFolder) ; Retrieve the relative path.
    If @error Then
        Return SetError(1, 0, $sTo)
    EndIf
    If $sRelativePath = '.' Then
        $sRelativePath &= '' ; This is used when the source and destination are the same directory.
    EndIf
    Return $sRelativePath
EndFunc   ;==>_PathGetRelativeEx

Example use of _PathFullEx:

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7
#include <File.au3>
#include <WinAPIEx.au3>  ; Download From http://www.autoitscript.com/forum/topic/98712-winapiex-udf/ by Yashied.

Local $hTimer = 0, $sFilePath = ''

$hTimer = TimerInit()
$sFilePath = _PathFull('.' & @ScriptName, @ScriptDir)
$hTimer = TimerDiff($hTimer)
ConsoleWrite('Original Path:      ' & '.' & @ScriptName & @CRLF & _
        'Full Path:          ' & $sFilePath & @CRLF & _
        '_PathFull() Time:   ' & $hTimer & @CRLF & @CRLF)

$hTimer = TimerInit()
$sFilePath = _PathFullEx('.' & @ScriptName, @ScriptDir)
$hTimer = TimerDiff($hTimer)
ConsoleWrite('Original Path:      ' & '.' & @ScriptName & @CRLF & _
        'Full Path:          ' & $sFilePath & @CRLF & _
        '_PathFullEx() Time: ' & $hTimer & @CRLF & @CRLF)

Func _PathFullEx($sRelativePath, $sBasePath = @WorkingDir) ; Created by guinness with the idea from _PathFull().
    Local $sWorkingDir = @WorkingDir
    _WinAPI_SetCurrentDirectory($sBasePath) ; Same as using FileChangeDir(). Change the working directory of the current process to the base path as _WinAPI_GetFullPathName() merges the name of the current drive and directory with the specified file name.
    $sRelativePath = _WinAPI_GetFullPathName($sRelativePath)
    _WinAPI_SetCurrentDirectory($sWorkingDir) ; Reset the working directory to the previous path.
    Return $sRelativePath
EndFunc   ;==>_PathFullEx

All of the above has been included in a ZIP file. _Path_ Functions (WinAPIEx).zip

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_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: 22/04/2018

Link to comment
Share on other sites

  • 11 months later...

I've updated the syntax of the following functions as well as the overall layout of the examples. Any suggestions for improvements then please post below. Thanks.

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_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: 22/04/2018

Link to comment
Share on other sites

_PathSplitEx() -> I still prefer this other solution:

; #FUNCTION# ====================================================================================================================
; Name...........: _PathSplitRegEx
; Description ...: Splits a path into the drive, directory, file name and file extension parts. An empty string is set if a part is missing.
; Syntax.........: _PathSplitRegEx($sPath)
; Parameters ....: $sPath - The path to be split (Can contain a UNC server or drive letter)
; Return values .: Success - Returns an array with 5 elements where 0 = original path, 1 = drive, 2 = directory, 3 = filename, 4 = extension
; Author ........: Gibbo
; Modified.......:
; Remarks .......: This function does not take a command line string. It works on paths, not paths with arguments.
;                This differs from _PathSplit in that the drive letter or servershare retains the "" not the path
;                RegEx Built using examples from "Regular Expressions Cookbook (O’Reilly Media, 2009)"
; Related .......: _PathSplit, _PathFull, _PathMake
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func _PathSplitRegEx($sPath)
    If $sPath = "" Then Return SetError(1, 0, "")
    Local Const $rPathSplit = '^(?i)([a-z]:|[a-z0-9_.$]+[a-z0-9_.]+$?)?((?:[^/:*?"<>|rn]+)*)?([^/:*?"<>|rn.]*)((?:.[^./:*?"<>|rn]+)?)$'
    Local $aResult = StringRegExp($sPath, $rPathSplit, 2)

    Switch @error
        Case 0
            Return $aResult
        Case 1
            Return SetError(2, 0, "")
        Case 2
            ;This should never happen!
    EndSwitch
EndFunc   ;==>_PathSplitRegEx
Anyway, thanks for sharing!

JS

http://forum.autoitbrasil.com/ (AutoIt v3 Brazil!!!)

Somewhere Out ThereJames Ingram

somewh10.png

dropbo10.pngDownload Dropbox - Simplify your life!
Your virtual HD wherever you go, anywhere!

Link to comment
Share on other sites

Thanks JScript for the function, a very different approach indeed.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_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: 22/04/2018

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...