File/Folder Check

I use this routine to check if a file or folder exists and whether the item is a file or a folder. This doesn’t use the Finder so it’s pretty fast and portable.

OS version: Any

set the_file to (((path to desktop) as string) & "filename")
set the_folder to (((path to desktop) as string) & "foldername:")

set file_info to get_item_info(the_file)
set folder_info to get_item_info(the_folder)

return {file_info, folder_info}

on get_item_info(the_path)
	try
		get the_path as alias
		set item_exists to true
	on error
		set item_exists to false
	end try
	if (the_path as string) ends with ":" then
		set item_type to "folder"
	else
		set item_type to "file"
	end if
	return {item_path:(the_path as string), item_type:item_type, item_exists:item_exists}
end get_item_info

Thanks Trash Man :smiley:

I was able to expand it to also return a “drive”-type

to getItemInfo(theFinderItem)
	try
		get theFinderItem as alias
		set itemExists to true
	on error
		set itemExists to false
	end try
	if (theFinderItem as string) ends with ":" then
		if (list disks) contains (((theFinderItem as string)'s characters 1 thru -2) as string) then
			set itemType to "drive"
		else
			set itemType to "folder"
		end if
	else
		set itemType to "file"
	end if
	return {itemPath:(theFinderItem as string), itemType:itemType, itemExists:itemExists}
end getItemInfo

Hi,

only for sports :wink:

on get_item_info(the_path)
	try
		set {isFolder, fName} to {folder, name} of (info for (the_path as alias))
		set item_exists to true
		set item_type to item ((isFolder as integer) + 1) of {"file", "folder"}
		if (list disks) contains fName and ((offset of ":" in the_path) is (length of the_path)) then set item_type to "volume"
		-- or if (list disks) contains fName and ((length of the_path) - (length of fName) < 2) then set item_type to "volume"
	on error
		set item_exists to false
		set item_type to missing value
	end try
	return {item_path:the_path, item_type:item_type, item_exists:item_exists}
end get_item_info

Edit: and here the mayhem version :wink:

...
try
	set {isFolder, fName} to {folder, name} of (info for (the_path as alias))
	set item_exists to true
	set item_type to item ((isFolder as integer) + (((list disks) contains fName and (length of the_path) - (length of fName) < 2) as integer) + 1) of {"file", "folder", "volume"}
on error
...