2008-08-04 124 views

回答

2

這是一個可以在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; 
} 
+1

可能需要更換`「\\」`和` File.separator`使它在Linux上工作。 – Kevin 2011-02-09 23:44:28

10

我也想嘗試:

File.userDirectory.name 

但我沒有安裝空調,所以我真的不能測試這個...

+0

在Windows XP上工作得很好。它會提供相同的Vista,Windows 7和iMac? – midhunhk 2011-09-14 08:15:10

+0

適用於Win 7的我 – Ilyssis 2014-11-29 17:36:52

10

有一對夫婦,你可以清理小的使...

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; 
     } 
    } 
} 

正如凱文建議,使用File.separator使目錄分裂的跨平臺(只在Windows和Mac OS X上測試過)。

除非您要找孩子,否則您不需要使用resolvePath("")

另外,使函數成爲一個適當的getter允許綁定,而無需進一步的工作。

在上面的例子中,我把它變成一個UserUtil類,現在我可以綁定到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> 
+2

當用戶具有不同的登錄名和主目錄名時,此解決方案不起作用,這在重新安裝或遷移操作系統時很常見。有誰知道另一種解決方案。請幫忙。 – 2011-02-09 23:46:46

-1

更新方式後:裏面居然是一個內置的函數來獲取當前用戶。我認爲這是在nativeApplication中。

5

這是不是最漂亮的辦法,但如果你知道你的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); 
} 
相關問題