How do I get the current username in .NET using C#?

后端 未结 18 1876
忘了有多久
忘了有多久 2020-11-22 09:59

How do I get the current username in .NET using C#?

18条回答
  •  面向向阳花
    2020-11-22 10:11

    For a Windows Forms app that was to be distributed to several users, many of which log in over vpn, I had tried several ways which all worked for my local machine testing but not for others. I came across a Microsoft article that I adapted and works.

    using System;
    using System.Security.Principal;
    
    namespace ManageExclusion
    {
        public static class UserIdentity
    
        {
            // concept borrowed from 
            // https://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity(v=vs.110).aspx
    
            public static string GetUser()
            {
                IntPtr accountToken = WindowsIdentity.GetCurrent().Token;
                WindowsIdentity windowsIdentity = new WindowsIdentity(accountToken);
                return windowsIdentity.Name;
            }
        }
    }
    

提交回复
热议问题