views:

35

answers:

2

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.

A: 

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.

Philip Regan
+1  A: 

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$"
regulus6633
Philip Regan
Yes, I know it works because in the beginning I did it this way too. Applescript is good that way... it helps correct minor mistakes. If you look at the result of the addition before it's coerced to a string it looks like this "{alias "Macintosh HD:Users:hmcshane:Desktop:", "file$"}". It's a list of 2 items so that's certainly not what we're after. Hopefully knowing the theory a little better will help with something more complex in the future that doesn't work.
regulus6633
I never thought of it that way, but yours is much cleaner. Thanks for the tip.
Philip Regan