OK, I thought this would be a simple one, but apparently I'm missing something obvious. My code is as follows:
set fileTarget to ((path to desktop folder) & "file$") as string
if file fileTarget exists then
display dialog "it exists"
else
display dialog "it does not exist"
end if
Easy right? Unfortunately, when I run the script it returns the error
Can’t get file "OS X:Users:user:Desktop:files$".
It doesn't matter if the file exists or not, this is the same error I get. I've tried a dozen different things but it still stumps me.
I use this subroutine to see if a file exists or not:
on FileExists(theFile) -- (String) as Boolean
tell application "System Events"
if exists file theFile then
return true
else
return false
end if
end tell
end FileExists
Add salt to taste.
It is easy except "exists" is a Finder or System Events command. It's not a straight applescript command. As such you must wrap it in a tell application code block. FYI: here's another way that doesn't require an application. It works because when you coerce a path to an "alias" it must exist otherwise you get an error. So you could do the following.
set fileTarget to (path to desktop folder as text) & "file$"
try
fileTarget as alias
display dialog "it exists"
on error
display dialog "it does not exist"
end try
NOTE: you have an error in your code. You're using the & operator to add strings but you're doing it wrong although you're getting the right answer by luck. When you use the & operator, each object on either side of the operator must be a string. "path to desktop folder" is not a string so we first must make that a string and then add the string "file$" to it. So do it like this...
set fileTarget to (path to desktop folder as text) & "file$"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With