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

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

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

相关标签:
18条回答
  • 2020-11-22 10:18

    In case it's helpful to others, when I upgraded an app from c#.net 3.5 app to Visual Studio 2017 this line of code User.Identity.Name.Substring(4); threw this error "startIndex cannot be larger than length of string" (it didn't baulk before).

    It was happy when I changed it to System.Security.Principal.WindowsIdentity.GetCurrent().Name however I ended up using Environment.UserName; to get the logged in Windows user and without the domain portion.

    0 讨论(0)
  • 2020-11-22 10:19

    Just in case someone is looking for user Display Name as opposed to User Name, like me.

    Here's the treat :

    System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName

    Add Reference to System.DirectoryServices.AccountManagement in your project.

    0 讨论(0)
  • 2020-11-22 10:22
    String myUserName = Environment.UserName
    

    This will give you output - your_user_name

    0 讨论(0)
  • 2020-11-22 10:23

    Get the current Windows username:

    using System;
    
    class Sample
    {
        public static void Main()
        {
            Console.WriteLine();
    
            //  <-- Keep this information secure! -->
            Console.WriteLine("UserName: {0}", Environment.UserName);
        }
    }
    
    0 讨论(0)
  • Try the property: Environment.UserName.

    0 讨论(0)
  • 2020-11-22 10:30

    You may also want to try using:

    Environment.UserName;
    

    Like this...:

    string j = "Your WindowsXP Account Name is: " + Environment.UserName;
    

    Hope this has been helpful.

    0 讨论(0)
提交回复
热议问题