2012-10-31 279 views
3

我正在制作一个程序,帮助工作人员在我的大学里检查和检查设备。我可以使用Enviroment.username,但作为一种学习体验,我希望获取当前登录用户的全名。按下windows按钮时看到的那个。所以我目前的playtest代码是:主要服务器故障

PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 
UserPrincipal user = UserPrincipal.Current; 
string displayName = user.DisplayName; 
Console.WriteLine(displayName); 
Console.ReadLine(); 

但它给了我一个主要的服务器下来的异常。我想这是权限问题,但我甚至不知道从哪里开始。

我能做些什么才能使这个工作?

+1

你是不是一个域名? – SLaks

回答

1

你有没有想过尝试这样

bool valid = false; 
using (var context = new PrincipalContext(ContextType.Domain)) 
{ 
    valid = context.ValidateCredentials(username, password); 
} 

的东西,如果你想获得更深入的,你可以做到这一点下面

using System.Security; 
using System.DirectoryServices.AccountManagement; 

public struct Credentials 
{ 
    public string Username; 
    public string Password; 
} 

public class Domain_Authentication 
{ 
    public Credentials Credentials; 
    public string Domain; 
    public Domain_Authentication(string Username, string Password, string SDomain) 
    { 
     Credentials.Username = Username; 
     Credentials.Password = Password; 
     Domain = SDomain; 
    } 

    public bool IsValid() 
    { 
     using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain)) 
     { 
      // validate the credentials 
      return pc.ValidateCredentials(Credentials.Username, Credentials.Password); 
     } 
    } 
} 
2

如果你的目的是要显示当前的属性用户...

UserPrincipal.Current抓取运行当前线程的Principal。如果这是有意的(例如使用模拟),那么您应该拥有用户数据,并且根本不需要设置主体上下文。

var up = UserPrincipal.Current; 
Console.WriteLine(user.DisplayName); 

但是,如果运行的线程的主体不是你想要的用户,你需要从一个域收集他们的帐户信息(即SLaks点),那么你就需要设置的主要背景和搜索它以获取适当的UserContext。

var pc = new PrincipalContext(ContextType.Domain, "domainName"); 
var user = UserPrincipal.FindByIdentity(pc, "samAccountName"); 
Console.WriteLine(user.DisplayName); 

您也可以使用其他IdentityType,如果你不喜欢的samAccountName:

var user = UserPrincipal.FindByIdentity(pc, IdentityType.Name, "userName"); 
// or 
var user = UserPrincipal.FindByIdentity(pc, IdentityType.Sid, "sidAsString"); 

如果您需要先手动认证用户,请参阅@使用principalContext.ValidateCredentials()

DJKRAZE的例子

祝你好运。

+0

谢谢,我确实希望运行线程的用户,但是up = UserPrincipal.Current给了我一个“PrincipalServerDownException”,如果我发现它给了我一个“服务器无法联系”的消息。 –

+0

UserPrincipal是DirectoryServices.AccountManagement的一部分,用于通过Active Directory(DS/LDS)处理用户/组/计算机帐户。因此,如果您的应用程序不在域中,您将没有服务器来查找您当前的“Principal”对象。不知道更多,我不能帮忙,但我猜像是SLaks,你使用本地帐户和/或你的机器没有连接到AD域。 –

+0

是啊,它没有连接到AD域,我的学校使用Linux域。但是我仍然可以通过转到开始按钮并查看我的全名来找到显示名称。这意味着它必须存储在某个地方。我只是想弄清楚。这个方法是我在stackoverflow上找到的一种方法。 –