If no base path is specified then a random alphanumeric string will be used of length "RandomLength".
If a base path is specified then it will be enumerated numerically by appending a string 0 to Limit at the end.
This isn't an end-all be-all solution. These two types of random directories are the kind I usually make; either random or enumerated. And that suits my needs.
Code: Select all
Procedure.s GetUniquePath(TargetPath.s, CreatePath.b=#False, BaseName.s="", RandomLength.a=32, Limit.l=1000000)
Protected NewPath.s
Protected i
;/ Verify that the path does not already exist
If Not FileSize(TargetPath.s)=-2
ProcedureReturn ""
EndIf
;/ Ensure a trailing slash
If Not Right(Trim(TargetPath.s,"/"),1)="\"
TargetPath.s+"\"
EndIf
;/ If the attempt limit is invalid then return
If Limit<= 0
;/ Failed
ProcedureReturn ""
EndIf
;/ If the random length is invalid and no base name is specified then return
If Not BaseName.s And RandomLength<= 0
;/ Failed
ProcedureReturn ""
EndIf
;/ If no base name is specified then use a random string of numbers and integers of length RandomLength
If Not BaseName.s
NewPath.s=""
Repeat
For i=1 To RandomLength
If Random(1)=1
NewPath.s+Chr(Random(25)+65)
Else
NewPath.s+Str(Random(9))
EndIf
Next i
Limit-1
;/ If the attempt limit has been reached then return
If Not Limit
;/ Failed
ProcedureReturn ""
EndIf
If CreatePath
;/ If the path was successfully created then return
If CreateDirectory(TargetPath.s+NewPath.s)
ProcedureReturn NewPath.s
EndIf
Else
;/ If the path was verified as available then return
If FileSize(TargetPath.s+NewPath.s)=-1
ProcedureReturn NewPath.s
EndIf
EndIf
ForEver
EndIf
For i=0 To Limit-1
NewPath.s=BaseName.s+Str(i)
If Len(NewPath.s)>255
ProcedureReturn ""
EndIf
If CreatePath
;/ If the path was successfully created then return
If CreateDirectory(TargetPath.s+NewPath.s)
ProcedureReturn NewPath.s
EndIf
Else
;/ If the path was verified as available then return
If FileSize(TargetPath.s+NewPath.s)=-1
ProcedureReturn NewPath.s
EndIf
EndIf
Next i
ProcedureReturn ""
EndProcedure