Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve first and last name of the current Windows user?

Tags:

java

I know you can retrieve the username with something like System.getProperty("user.name") but I am looking for a way to retrieve the first and last name of the current user.

Is there a native Java library that does this? Or do you have to plug into the Windows API? Or maybe you have to pull it from Active Directory? This seems relatively easy with .NET but I can't find a way to do it in Java.

like image 736
aus Avatar asked Feb 10 '12 17:02

aus


2 Answers

As Brian Roach suggested in the comments, it's pretty straight-forward to do this with JNA, since it has a built-in wrapper for Secur32 which wraps the GetUsernameEx() function (which is ultimately the system call wrapped by the .NET library you linked to above).

Use would be something like this:

import com.sun.jna.ptr.IntByReference;
import com.sun.jna.platform.win32.Secur32;

// ...    

char[] name = new char[100];  // or whatever is appropriate
Secur32.INSTANCE.GetUserNameEx(
     Secur32.EXTENDED_NAME_FORMAT.NameDisplay,
     name,
     new IntByReference(name.length)
);

String fullName = new String(name).trim();

Note that this will give you the full name in the same format as you'd get typing net user %USERNAME% /domain at the command prompt.

like image 196
ig0774 Avatar answered Nov 01 '22 17:11

ig0774


Or just,

String fullName = Secur32Util.getUserNameEx(Secur32.EXTENDED_NAME_FORMAT.NameDisplay);

But it is the same, as the upper answer

like image 37
serg Avatar answered Nov 01 '22 16:11

serg