How to write to a text file in ActionScript 3.0?

actionscript, actionscript-3

Solution

Saving to a text file is possible (using the File class in AIR) but this is really not a great approach. Instead you should checkout the SharedObject class

Quick example:

 var sharedObject:SharedObject = SharedObject.getLocal("userInfo"); //this will look for a shared object with the id userInfo and create a new one if it doesn't exist

Once you have a handle on your sharedObject

sharedObject.data.userName = "Some username";
sharedObject.data.password= "Some password"; //it's really not a good idea to save a password like this
sharedObject.flush(); //saves everything out

Now to get your data back, elsewhere in the code

var sharedObject:SharedObject = SharedObject.getLocal("userInfo");
trace(sharedObject.data.userName);
trace(sharedObject.data.password);

This object is saved locally to the users computer. It's very similar to a browser cookie.

Now saving out a password to this object in plain text is not a good idea. A better plan would be to validate the login information on a server and store a session id of some kind in this object.

in pseudo code:

function validateLogin(){
    var sessionID = server->checkLogin(username, password); //returns a string if authed, nothing if not
    if(sessionID){
         sharedObject->sessionID = sessionID;
    } else {
        //bad login
    }
}

More reading:

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html

http://www.republicofcode.com/tutorials/flash/as3sharedobject/

Problem

I'm working on a method of authentication, and i have 2 text fields named 'username' and 'pass' I want to make it so that when the user enters their username and password, that info gets stored into a text file. So when they log back in, it reads the username and password from that text file to log in. How can I do this? Thanks :D

Original source