The following line of code in my C#, .NET 5.0 Windows application throws an exception when my application runs normally but not when it runs as Administrator.
var pc = UserPrincipal.Current.Context;
The message in the exception is "The server could not be contacted". I am unable to determine the exact type of the exception because this is happening in the field and I'm looking at a log file which sadly fails to log that detail. I have been unable to reproduce this myself. So I'm looking for some "defensive programming" to hopefully get around it.
Is this something that I can make work without running as Administrator? Is there some "safer" way to try to get the current context? The only reason I'm trying to get it in the first place is to get a "friendly" name for the current user. Like UserPrincipal.DisplayName
or UserPrincipal.Surname
?
When I run normally. this is the stack frame of the exception
09:26:21.799 [ 1] ERROR - RegisterTypes: Exception Registering types: The server could not be contacted.
at System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties)
at System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval()
at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String container, ContextOptions options, String userName, String password)
at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType)
at System.DirectoryServices.AccountManagement.UserPrincipal.get_Current()
at MyApp.Services.SystemService.Initialize()
at MyApp.Mobile.App.RegisterTypes(IContainerRegistry reg)