我需要Air/Flex应用程序中当前登录用户的名称。该应用程序将仅部署在 Windows 机器上。我想我可以通过正则表达式用户目录来实现这一点,但我对其他方式持开放态度。
5 回答
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>
我也会尝试:
File.userDirectory.name
但我没有安装 Air,所以我无法真正测试这个......
这不是最漂亮的方法,但如果您知道您的 AIR 应用程序只能在 Windows 环境中运行,它就足够了:
public var username:String;
public function getCurrentOSUser():void
{
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = new File("C:/WINDOWS/system32/whoami.exe");
nativeProcessStartupInfo.executable = file;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.start(nativeProcessStartupInfo);
}
public function onOutputData(event:ProgressEvent):void
{
var output:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
this.username = output.split('\\')[1];
trace("Got username: ", this.username);
}
这是一个适用于 XP / Vista 的解决方案,但绝对可以扩展到 OSX、Linux,我仍然对另一种方式感兴趣。
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;
}
稍后更新:实际上有一个内置函数可以获取当前用户。我认为它在 nativeApplication 中。