7. How do I retrieve the current Windows user account name in C#?
First of all, there's no need to start pinvoking just to get the Windows user account
name from a C# program: It's right there buried in the class hierarchy like just about
everything else. However what you get may not be what you need. Let me explain.
The key is System.Security.Principal.WindowsIdentity. The code below shows how
we can access it.
using System.Windows;
using System.Windows.Forms;
using System.Security.Principal;
// blah, blah, class stuff...
public string GetWindowsUserName ()
{
string UserIdWithDomain = WindowsIdentity.GetCurrent().Name.ToString();
string Result;
int PosSlash = UserIdWithDomain.IndexOf('\\');
if (PosSlash == -1)
Result = UserIdWithDomain;
else
Result = UserIdWithDomain.Substring(PosSlash + 1, UserIdWithDomain.Length - (PosSlash + 1));
return Result;
}
However the GetCurrent().Name property doesn't just give you the username, it gives you
domain\username. If you want just the name (say for DB login purposes), you need
to extract it. The function above detects the domain terminating backslash and
removes it, giving you just the current user account name. Have a look at the docs
for WindowsIdentity, there's some interesting stuff in there.