Check if folder exists?

Hey all,

I have a silly little project on the go to try and teach myself about folders.

Using the examples that came with xojo i have an application that gets the contents of a folder and populates the listbox with the name of the contents.

But what I am currently stuck on is if I delete the folder from my computer. It is crashing the app.

I’ve tried the following code.

Var dlg As FolderItem = SpecialFolder.UserHome
Var c As FolderItem

c = dlg.Child("appdata\Roaming\Vortex\downloads\")

arrayList.RemoveAllRows

For Each file As FolderItem In c.Children
  if dlg.Exists then
    arrayList.AddRow(file.Name)
  end if
next
else
msgbox("This folder does not exist!")

end if

If anyone could offer any guidance it would be greatly appreciated!

Robin

i guess you are not deleting UserHome :wink:
that dlg.Exists look odd

try

var path As FolderItem = dlg.Child("appdata\Roaming\Vortex\downloads\")
if path.Exists
1 Like

You need to be starting with the correct special folders, and only dig one child at a time. Using Child with a path like that leads to unstable results.

SpecialFolder.ApplicationData will get you into \AppData\Roaming\ so start there. I usually use a function to return my application specific folder or create it if necessary. Kind of like this:

var fAppData as FolderItem = SpecialFolder.ApplicationData
fAppData = fAppData.Child("Vertex")

// Be sure you have your app data folder
if not fAppData.Exists then
  fAppData.CreateAsFolder

end

return fAppData

(written in post editor, subject to bugs/renames)

1 Like

Child takes a name, not a path.

@Tim_Parnell
he wrote it works until he delete his folder.
but

Var dlg As FolderItem = SpecialFolder.UserHome
if dlg.Exists then

is for sure wrong.

I can offer nothing more. Child does not take a path, it just unintentionally occasionally works. It is the furthest thing from cross platform or debuggable, but sure.

Thank you @Tim_Parnell and @MarkusR

I’ve defiantly learnt something more about folder items.

Note in the documentation for FolderItem.Constructor(path as String, pathMode as FolderItem.PathModes, followAlias as Boolean = true):

If Path cannot be resolved to a FolderItem, an UnsupportedFormatException is raised. This is notably the case when a folder does not exist within the given Path or when you do not have the correct access permissions for something in the path. Only the last component of the path is allowed not to exist.

This lets you specify a folder or file that doesn’t exist yet (so you can create it), but not whole potentially non-existent paths.This same sort of issue with folderitems will cause problems elsewhere. This is why, as @Tim_Parnell notes, you should walk down the hierarchy with .Child("name") one step at a time, testing for nil.

Forum for Xojo Programming Language and IDE. Copyright © 2021 Xojo, Inc.