read path from text and set as background

hello
I am trying to create a script which will read from a text file the path and then set this path as wallpaper.
I had this script which set the background
I am doing something like this but i am get the error:System Events got an error: current desktop doesnt understand the readFile message

on readFile()

set foo to (open for access (POSIX file “Mac OS X:Users:mixalismavris:Desktop:ecd.rtf”))

set txt to (read foo for (get eof foo))

close access foo

return txt

end readFile
tell application “System Events”
– SET DESKTOP TO SPECIFIC PICTURE
tell current desktop
set picture rotation to 0 – (0=off, 1=interval, 2=login, 3=sleep)
set x to readFile()
set picture to file x

end tell
end tell

also i have tried: set picture to file readFile()
but is not working
anybody know how is works this?
thanks anyway

The first problem regarding the ‘doesn’t understand…’ message comes because AppleScript is trying to send your ‘readfile()’ command to System Events rather than the handler in your own script.

This is because you are in a ‘tell application “System Events”’ block.

The solution is simple - be more specific and tell AppleScript that you want your readfile() handler and not System Events’:

set x to my readfile()

Now, as for the readfile() handler itself, it’s very verbose. You can read the entire contents of a file in one line via:

on readfile()
set txt to read file (POSIX file "Mac OS X:Users:mixalismavris:Desktop:ecd.rtf")
return txt

The ‘open for access’/‘close access’ is only really needed if you’re doing block reads (reading the file in parts, rather than all at once), or planning on writing data to the file.

The second question I have is whether this will work at all. Since your file is a RTF file it is likely to have all sorts of other text within it for the formatting. Even a plain-looking RTF file can have many bytes of extra data just to say ‘hey, this is a plain text file’.

At the very, very least you need to look at the raw contents of that file to make sure it contains only the data you need.
If it does contain extra code your options are to either parse the RTF (not easy), or use a plain text file rather than a RTF file (easy).

Once you’ve verified that you have the right data in the file, the rest of your code should work.