Just a question: how do you know (report) where the error is if you concatenate .Child in a single line ?
That is areason I try to avoid one liners (the second is… in the old BASIC times - 1980 and before - there was people fighting to be the one who do more instructions per line…)
But, this is me.
The location of the error is pretty simple. You want the compiler to read the code as (New FolderItem(Path, Mode)).Child(Name) but it does not. It reads it more like New (FolderItem(Path, Mode).Child(Name)). Neither works. You can’t create a new instance and immediately start chaining off it. Xojo just can’t do it.
The closest you could come is CType(New FolderItem(Path, Mode), FolderItem).Child(Name) but… no don’t do that.
If I call a function to get back a FolderItem like CreateFolderItem(Path as String).Child(“dir1”).Child(“dir2”).Child(“dir3”).Child(“file.txt”) it doesn’t work
That’s not a new behavior, though a change was made on a Mac to match the limitations of Windows.
The first call to Child works fine because the parent exists. The second call does not because the first does not exist.
Basically, FolderItem.Exists must be true to get a child. There was a discussion here recently about it. I personally think it’s a stupid limitation, but it’s one we have to contend with nevertheless.
Don’t do that. Somewhere along the path to the file you may encounter a folder that doesn’t exist and when that happens the next Child call will fail.
If the folder hierarchy is managed by your application you would check for each folder to exist and if it doesn’t you would create it. If the folder hierarchy is beyond your control but you expect all the folders and subfolders to exist you could simply catch the exception and report the problem to the user.
In situations like the first case (i.e. I am managing the folder hierarchy) I’m often using a global method EnsureFolderExists that drills down a chain of subfolders, making sure all those subfolders exist by creating them if necessary. It returns the deepest subfolder if successful and nil otherwise:
Public Function EnsureFolderExists(f as FolderItem, ParamArray Subfolders as String) As FolderItem
if not f.Exists then return nil
var NumberOfSubfolders as Integer = Subfolders.LastIndex
for i as Integer = 0 to NumberOfSubfolders
f = f.Child(Subfolders(i))
if not f.Exists then
f.CreateFolder
if not f.Exists then return nil
end if
next
return f
End Function
This would get called like
var myFolder, myFile as FolderItem
myFolder = EnsureFolderExists(CreateFolderItem(Path), "dir1", "dir2", "dir3")
if not(myFolder is nil) then
myFile = myFolder.Child("file.txt")
end if