Search code examples
flashactionscript-3file-formatxml

Prevent user from including file extension in file name in air application


So I have an air application that I want to save data from into an custom file. Below is my code. My question is, this code is checking if the user has not typed the ".bar" in their file name, and if they haven't, the program will add it onto the end of the file name.

My question is, if a user types "newFile.foo", it saves the file as "newFile.foo.bar". How can I prevent either the user from typing an extension, or maybe have the application remove the ".foo" part, or any other option that will achieve the desired results.

Thanks.

var file:File = File.desktopDirectory
file.browseForSave("Save");// Create a <projectStrings /> node
var projectStrings:XML = new XML(<projectStrings />);
// Create a <strings /> node
var strings:XML = new XML(<strings />);
strings.@stringOne = "Hello";
strings.@stringTwo = "World";
// Add the <strings> node to the <projectStrings> node.
projectStrings.appendChild(strings);

var saveFile:File = File(e.target);
var directory:String = saveFile.url;
if (directory.indexOf(".ugags") == -1) {
    trace("WRONG");
    directory += ".ugags";
}
var file:File = new File(directory);
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeUTFBytes(projectStrings);
fileStream.close();

Solution

  • You can use lastIndexOf String's method to detect file's extension like that:

    var nameStart:int = Math.max(fileName.lastIndexOf("/"), fileName.lastIndexOf("\"));
    var extStart:int = fileName.lastIndexOf(".");
    if (ext <= nameStart)
    {
      //no extention at all
      fileName += ".foo";
    }
    else
    {
      if (fileName.substr(extStart) != ".foo")
      {
        //user given other extension
      }
    }