Sunday, March 13, 2011

Files and directories in AIR: Part 3

Today we will learn how to create directories on the user's computer using AIR.

We can do that by first specifying the location and then calling a function called createDirectory(). Example:

import flash.filesystem.File;

var exampleDirectory:File = File.documentsDirectory.resolvePath("Air Examples/Example");
exampleDirectory.createDirectory();

The code above will go to the documents folder and create there a directory called Air Examples and another directory called Example inside it. If we already have the folder with the name we've specified - createDirectory() won't do anything. For example, if we have a directory Air Examples in the same path and run the code - a folder called Example will be created in the already existing Air Examples directory. It will also not overwrite any of the folder's contents, so this makes createDirectory() a pretty safe method.

Even though we won't overwrite any existing content, if we want to create a directory using AIR we probably want to put something in it. This way, if we have, for example, an application for creating icons, we would want to create a folder called Icons to store all the created pictures in. If the user already has a folder Icons before we created it, we probably shouldn't use it, because then his previous and the new generated files will be mixed up in one directory.

That's why we want to check if the directory exists first and if it does - pick a different name for the folder.

We can check if a folder exists using the exists property:

trace(exampleDirectory.exists);

This way we create folders with new names every time:

import flash.filesystem.File;

var exampleDirectory:File = File.documentsDirectory.resolvePath("My Example");
var num:int = 1;

while(exampleDirectory.exists){
exampleDirectory = File.documentsDirectory.resolvePath("My Example(" + num + ")");
num++
}

exampleDirectory.createDirectory();

If we run the code above several times, directories like this will be created:



Thanks for reading!

Related:

Files and directories in AIR: Part 1
Files and directories in AIR: Part 2
Files and directories in AIR: Part 4
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