2016-11-23 7 views
2

Active Directoryからユーザー名を取得しようとしています。私はこのコードを試してみましたが、Userの部分がUser.Identity.Nameであると認識していません。私は別の参照またはアセンブリを追加する必要があるかどうかを見てきましたが、何も見たことはありません。 Active Directoryからユーザー名を取得するより良い方法はありますか?Active Directoryからユーザー名を取得する

static string GetUserName(){ 

     string name = ""; 
     using (var context = new PrincipalContext(ContextType.Domain)) 
     { 
      var usr = UserPrincipal.FindByIdentity(context, User.Identity.Name); 
      if (usr != null) 
       name = usr.DisplayName; 
     } 

    } 

答えて

1

あなたはWindowsIdentity.GetCurrent

を使用することができます
using System.Security.Principal; 

static string GetUserName() 
{ 
    WindowsIdentity wi = WindowsIdentity.GetCurrent(); 

    string[] parts = wi.Name.Split('\\'); 

    if(parts.Length > 1) //If you are under a domain 
     return parts[1]; 
    else 
     return wi.Name; 
} 

用途:

string fullName = GetUserName(); 

あなたを助けて幸せ!

+0

私は、これはwi.Name.Split'は、あなたが参照している –

+0

が認識されない 'で' wi'してみてください「System.Security.Principalを使用して、」? –

+0

はい私はそれを参照しています。それは言う - フィールド初期化子は、非静的なフィールド、メソッド、またはプロパティを参照できません 'OpenBurn.Controllers.RequestBurnsController.wi' –

0

方法について:何らかの理由で

public string GetUserName() 
{ 
    string name = ""; 

    using (var context = new PrincipalContext(ContextType.Domain)) 
    { 
     var usr = UserPrincipal.Current; 

     if (usr != null) 
     { 
      name = usr.DisplayName; 
     } 
    } 
} 
関連する問題