C# 在自动运行应用程序中从AD检索全名

C# 在自动运行应用程序中从AD检索全名,c#,active-directory,C#,Active Directory,我正在尝试检索当前登录的用户的全名 我发现,它通常可以很好地处理这个小片段: [Export(typeof(IAdManager))] public class AdManager : IAdManager { public string GetFullName() { try { DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDoma

我正在尝试检索当前登录的用户的全名

我发现,它通常可以很好地处理这个小片段:

[Export(typeof(IAdManager))]
public class AdManager : IAdManager
{
    public string GetFullName()
    {
        try
        {
            DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName);
            return de.Properties["fullName"].Value.ToString();
        }
        catch
        {
            return string.Empty;
        }
    }
}
不幸的是,当我试图在Windows start上启动应用程序时,它停止工作。结果是一个空(或null?)字符串

我在这里放了一条捷径:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

有什么想法,为什么它不起作用?这是因为该位置在用户登录之前实际加载了应用程序吗?

请尝试直接从AD获取
全名

public static string GetFullName()
{
   using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
   {
      string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
      using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username))
      {
         if (user != null)
         {
            return user.DisplayName;
         }
      }
   }
   return null;
}

谢谢你,我很感谢你的帮助:)我已经用UserPrincipal.Current.DisplayName解决了我的问题,但我希望你的回答对其他人有所帮助。