Check whether a directory is drive or write-protected
This lesson demonstrates how to check whether a directory or drive is write protected. This can be useful to check when asking the user to choose a file to save to so the application can inform them if they choose a protected location.
The canWriteFileTo function
The canWriteTo function takes a single parameter, pFolder, and returns true if the directory is writable, false otherwise.
The function is called with code such as the following:
if canWriteFileTo(specialFolderPath("Preferences")) then createPrefsFile else answer "Could not create a Preferences file." end if
Checking the attributes
The function does not directly check the attributes of the directory. Instead, it uses a trick: it tries to create a file, using the open file command. When you use the open file command and specify a nonexistent file, the command creates the file.
Note: if you wanted to directly read the permissions attribute of a directory instead, you can use the detailed folders function.
If the command fails, indicating no file can be created in that location, the result function will return an error message. By checking whether the result is empty, we can check whether the open file command was successful, and therefore whether it's possible to create a file at the desired location.
Generating a random file name
We don't want to use a file that might already exist in the specified folder. For this reason, the handler generates a random number between 1 and 9999, using the random function. The file's name consists of the string "temp" followed by this random number. It's very unlikely that there will already be a file with such a name. Additionally, if the file is accidentally left in place after the handler finishes executing, at least its name clearly indicates that it is a temporary file and can be removed.
If the result is empty, the command succeeded. The handler then cleans up after itself by closing and deleting the test file. If the result is not empty, the file wasn't created, so it doesn't need to be cleaned up.
The canWriteToFile function code
function canWriteFileTo pFolder local tRandomFileName put pFolder & "/temp" & random(9999) into tRandomFileName open file tRandomFileName for write ## try creating a file if the result is empty then ## success ## get rid of the test file close file tRandomFileName delete file tRandomFileName return true else ## failed - couldn't create a file there return false end if end canWriteFileTo
Add your comment