Search code examples
applescriptposixdropboxaccess-deniedfolder-permissions

Can't set the_folder to a user folder (access denied)


I've searched for a couple of hours now, and every time I try a recommended fix. I still can't get anywhere. I feel like I'm missing something so obvious, my Mac is laughing at my poor attempts.

Here's the script:

tell application "System Events"
set the_folder to path to folder "dropbox" from user domain as string
set the_file to "ToDo.txt" of (POSIX path of the_folder)
set the_text to (do shell script "cat " & quoted form of (POSIX path of the_file))
return the_text
end tell

The results:

Can’t get "ToDo.txt" of (POSIX path of the_folder). Access not allowed.

It doesn't matter what the folder is, either. I've tried with Documents/Library and still always get that access issue.


Solution

  • Here's a corrected version of your script:

        tell application "System Events"
            set the_folder to the folder "~/Dropbox"
            set the_file to the file "ToDo.txt" in the_folder
    
            set the_text to do shell script "cat " & ¬
                quoted form of (POSIX path of the_file as text)
        end tell
    
        return the_text
    

    The points to note are as follows:

    1. Don't use Path To for folders that aren't referenced by a builtin AppleScript constant, such as home folder or desktop folder. Instead, I changed the line to a simple reference to a folder object with the specified path "~/Dropbox".
    2. Similarly, you need to place a file object specifier before stating the name of the file, otherwise all you've done is given System Events a piece of text and said that text is somewhere in the folder (which doesn't make a whole lot of sense). Now I've told System Events that it's a file and the text is the file's name, it knows exactly where to find it.
    3. Lastly, for some reason, you need to state that the POSIX path of the_file is of type class text. I don't really know why AppleScript can't see it is already text, but that's the way it is sometimes.

    Now I'm going to show you another script that will do exactly what yours does:

        set the_text to read (POSIX path of ¬
            (path to home folder) & ¬
            "Dropbox/ToDo.txt" as POSIX file as alias)