Monday, 12 April 2010

Get name of current Windows user

This function returns a string of the currently logged in user on Windows. An empty string is returned if a valid name cannot be obtained.

   1:  /// <summary>
   2:  /// Returns the name of the currently logged on Windows user.
   3:  /// </summary>
   4:  /// <returns>
   5:  /// Current user logon name string. Returns an empty string if a valid name cannot be obtained.</returns>
   6:  private static string GetWindowsUserName()
   7:  {
   8:      System.Security.Principal.WindowsIdentity win_id = null;
   9:      string userName = String.Empty;
  10:   
  11:      try
  12:      {
  13:          // Get an object with details about the currently logged on Windows user.
  14:          win_id = System.Security.Principal.WindowsIdentity.GetCurrent();
  15:   
  16:          // Get current user domain name and logon name strings.
  17:          // [0] = Domain name.
  18:          // [1] = Logon name.
  19:          string[] names = win_id.Name.Split(new Char[] { '\\' }); // win_id.Name returns "Domain\Logon"
  20:   
  21:          if (names.Length == 2) { userName = (names[1]); }
  22:      }
  23:      catch (System.Security.SecurityException)
  24:      {
  25:          // Retrieving Windows user details failed so ensure returned name is an empty string.
  26:          userName = String.Empty;
  27:      }
  28:      finally
  29:      {
  30:          // Dispose of windows identity object.
  31:          if (win_id != null) { win_id.Dispose(); }
  32:      }
  33:   
  34:      return userName;
  35:  }

0 comments: