benners

[Solved] Using _WinAPI_CreateDirectory Recursively

3 posts in this topic

#1 ·  Posted (edited)

I know I can use DirCreate() to create a full path structure, but if the function errors there is no "real" error message. Using dllcall() and CreateDirectoryW yields the same result.

I started to use _WinAPI_CreateDirectory for _WinAPI_GetLastErrorMessage which gives me a bit of help when trying to figure out issues, and gives a readable string to log. As

the function doesn't create intermediate directories, only the final one, it fails if any directories are missing bar this final one. I had a play and made a simple function to check and create any missing intermediate directories and was wondering how this can be improved and made more robust.

If anyone can suggest improvements or a better way then please do

#include <WinAPI.au3>
#include <WinAPIFiles.au3>

Local $s_Path = 'C:\Users\Benners\AppData\Local\Temp\OI\Updates\KB2956084'
Local $v_Ret = _Directory_CreateRec($s_Path)

MsgBox(0, @error, $v_Ret)

Func _Directory_CreateRec($s_Path)
    If FileExists($s_Path) Then Return 1

    ; check for ANSI max path length (alter for unicode length)
    if StringLen($s_Path) > 248 then Return SetError(1, 0, 'File path exceeds max path length of 248 for ANSI')

    Local $as_Path = StringSplit($s_Path, '\')
    If Not IsArray($as_Path) Then Return SetError(2, 0, 'Unable to split ' & $s_Path) ; should always be an array

    Local $i_Count = 1 ; set to skip root
    Local $s_Check = $as_Path[$i_Count] ; set starting path

    Do
        If Not FileExists($s_Check) Then
            If $i_Count = 1 Then Return SetError(3, 0, 'Root drive ' & $s_Check & ' was not found') ; skip if root missing

             ; try to create dir. Probably a better way than returning in the loop
            If Not _WinAPI_CreateDirectory($s_Check) Then Return SetError(_WinAPI_GetLastError(), 0, _WinAPI_GetLastErrorMessage())
        Else
            $i_Count += 1 ; increase to check for next path
            If $i_Count <= $as_Path[0] Then $s_Check &= '\' & $as_Path[$i_Count]
        EndIf
    Until $i_Count > $as_Path[0]

    ; one final check 'cos I'm error paranoid
    If Not FileExists($s_Path) Then Return SetError(4, 0, 'Issues with directory creation')
    Return 1
EndFunc   ;==>_Directory_CreateRec

 

Edited by benners

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