Reputation: 787
I am struggling with yet another simple task in the Windows 10 UWP world.
I simply need the UserName of the current Windows user. Environment.UserName is just not a thing in UWP. And no amount of searching the web has helped so far. Hence my post here.
Anyone? Is this just not possible now?
Upvotes: 14
Views: 15710
Reputation: 112
// get username
public string UserNameStr { get; set; } = WindowsIdentity.GetCurrent().Name;
This will get you the full domain\username.
Upvotes: 7
Reputation: 687
Use this code to get user display name:
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
IReadOnlyList<User> users = await User.FindAllAsync();
var current = users.Where(p => p.AuthenticationStatus == UserAuthenticationStatus.LocallyAuthenticated &&
p.Type == UserType.LocalUser).FirstOrDefault();
// user may have username
var data = await current.GetPropertyAsync(KnownUserProperties.AccountName);
string displayName = (string)data;
//or may be authinticated using hotmail
if(String.IsNullOrEmpty(displayName))
{
string a = (string)await current.GetPropertyAsync(KnownUserProperties.FirstName);
string b = (string)await current.GetPropertyAsync(KnownUserProperties.LastName);
displayName = string.Format("{0} {1}", a, b);
}
text1.Text = displayName;
}
Upvotes: 21
Reputation: 81
You can also pickup the User who launched the app from the Application.OnLaunched method see here.
You still need to declare the User Information capability in you manifest though.
quick example (Ellipses denote non applicable generated code):
sealed partial class App : Application
{
...
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
User currentUser = e.User;
...
}
...
}
Upvotes: 2
Reputation: 1195
As I can see, there is a User
class available (UWP): https://msdn.microsoft.com/en-us/library/windows/apps/windows.system.user.aspx
Try this:
var users = await User.FindAllAsync(UserType.LocalUser);
var name = await users.FirstOrDefault().GetPropertyAsync(KnownUserProperties.AccountName);
Upvotes: 5