Monday, March 14, 2011

Files and directories in AIR: Part 4

Today we'll learn how to remove directories and files from the user's computer using AIR.

To delete a file or a directory from the user's hard drive, you can use methods deleteDirectory(), deleteDirectoryAsync(), deleteFile() and deleteFileAsync(). These methods remove the files completely and there is no way to get them back. This is why you should be very careful about deleting stuff.

These methods are best used in situations, when AIR creates its own temporary folders and files that user doesn't know about and later needs to delete them.

In this example, I create a directory and remove it:

import flash.filesystem.File;

var tempFile:File = File.documentsDirectory.resolvePath("Temporary Folder");
tempFile.createDirectory();

tempFile.deleteDirectory();

When deleting directories, by default the methods will only delete empty directories. If they have any contents - they will stay untouched. If you want to remove the folder with its contents, pass the 'true' parameter to deleteDirectory() or deleteDirectoryAsync().

There are two ways of removing a file or a directory - synchronously and asynchronously. The difference between the two is that if you are removing something synchronously, your code works as it is written - step by step, and when the deletion function is reached - you'll have to wait for the file to be removed completely before the rest of the code will be read and executed.

When removing something asynchronously, the file is being removed without depending on the code. This is especially useful when removing big files.

It is also possible to move a file/directory to trash instead of simply deleting it. This is a safer way of removing things - the user has the backups if he realised that he removed the wrong files and then he can easily get his files back. The methods are moveToTrash() and moveToTrashAsync(). They don't require parameters and simply move the file or directory to the trash. The first method does it synchronously, the second - asynchronously.

And that's all for now.

Thanks for reading!

Related:

Files and directories in AIR: Part 1
Files and directories in AIR: Part 2
Files and directories in AIR: Part 3
Files and directories in AIR: Part 5
Files and directories in AIR: Part 6
Files and directories in AIR: Part 7
Files and directories in AIR: Part 8
Files and directories in AIR: Part 9
Files and directories in AIR: Part 10
Files and directories in AIR: Part 11
Create a log application using XML and AIR: Part 1
Create a log application using XML and AIR: Part 2
Create a log application using XML and AIR: Part 3
Create a log application using XML and AIR: Part 4
Files and directories in AIR: Part 12

No comments:

Post a Comment