Applescript testing for file existence

EightQuarterBit picture EightQuarterBit · Aug 12, 2010 · Viewed 28.1k times · Source

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.

Answer

Philip Regan picture Philip Regan · Aug 12, 2010

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.