tags:

views:

1331

answers:

7

I need the name of the current logged in user in my Air/Flex application. The application will only be deployed on Windows machines. I think I could attain this by regexing the User directory, but am open to other ways.

+1  A: 

Here is a solution that works in XP / Vista, but is definitely expandable to OSX, linux, I'd still be interested in another way.

    public static function GetCurrentOSUser():String{
// XP & Vista only.
var userDirectory:String = File.userDirectory.resolvePath("").nativePath;
var startIndex:Number = userDirectory.lastIndexOf("\\") + 1
var stopIndex:Number = userDirectory.length;
var user = userDirectory.substring(startIndex, stopIndex);
return user;
}
Shawn Simon
+1  A: 

May want to replace \ with File.separator to make it work on linux.

Kevin
+2  A: 

Also I would try:

File.userDirectory.name

But I don't have Air installed so I can't really test this...

Kevin
+3  A: 

There's a couple of small cleanups you can make...

package
{
    import flash.filesystem.File;

    public class UserUtil
    {
     public static function get currentOSUser():String
     {
      var userDir:String = File.userDirectory.nativePath;
      var userName:String = userDir.substr(userDir.lastIndexOf(File.separator) + 1);
      return userName;
     }

    }
}

As Kevin suggested, use File.separator to make the directory splitting cross-platform (just tested on Windows and Mac OS X).

You don't need to use resolvePath("") unless you're looking for a child.

Also, making the function a proper getter allows binding without any further work.

In the above example I put it into a UserUtil class, now I can bind to UserUtil.currentOSUser, e.g:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Label text="{UserUtil.currentOSUser}"/> 
</mx:WindowedApplication>
ianmjones
A: 

Update way later: there's actually a built in function to get the current user. I think it's in nativeApplication.

Shawn Simon
I need to get the current user too, but can't find that function... can you share the solution?
Cosma Colanicchia
i can't find it : \
Shawn Simon
+1  A: 

This solution doesnť work when the user has different login name and home directory name, which is common when OS is reinstalled or migrated. Does anyone know another solution. Please help.

Jan Smutny
A: 

Regarding Shawn Simon's answer - can you spell out to me, how to obtain the o/s username of the currently logged-in user using nativeApplication in Adobe AIR ? Thank in advance!

tbsalling