Remove domain information from C # login ID

I would like to remove the domain / computer information from the login ID in C #. So, I would like to make "Domain \ me" or "Domain \ me" just "me." I could always check for existence and use this as an index to run a substring ... but I'm looking for something more elegant and compact.

Worst scenario:

int startIndex = 0; int indexOfSlashesSingle = ResourceLoginName.IndexOf("\"); int indexOfSlashesDouble = ResourceLoginName.IndexOf("\\"); if (indexOfSlashesSingle != -1) startIndex = indexOfSlashesSingle; else startIndex = indexOfSlashesDouble; string shortName = ResourceLoginName.Substring(startIndex, ResourceLoginName.Length-1); 
+17
string c # indexof
09 Oct '08 at 1:08
source share
8 answers

when you have a hammer, everything looks like a nail .....

use razor blade ----

 using System; using System.Text.RegularExpressions; public class MyClass { public static void Main() { string domainUser = Regex.Replace("domain\\user",".*\\\\(.*)", "$1",RegexOptions.None); Console.WriteLine(domainUser); } } 
+35
09 Oct '08 at 2:29
source share

You can abuse the Path class as follows:

 string shortName = System.IO.Path.GetFileNameWithoutExtension(ResourceLoginName); 
+23
Oct 09 '08 at 2:52
source share

What about:

 string shortName = ResourceLoginName.Split('\\')[1] 
+4
May 02 '11 at 15:25
source share

I always do this:

  string[] domainuser; string Auth_User = Request.ServerVariables["AUTH_USER"].ToString().ToLower(); domainuser = Auth_User.Split('\\'); 

Now you can look at the domainuser.Length domain to find out how many parts and domainuser [0] are for the domain and domainuser [1] is for the username.

+3
09 Oct '08 at 1:13
source share
  string theString = "domain\\me"; theString = theString.Split(new char[] { '\\' })[theString.Split(new char[] { '\\' }).Length - 1]; 
+2
Oct 09 '08 at 1:17
source share

This will work with both names and names.

 ^(?<domain>.*)\\(?<username>.*)|(?<username>[^\@]*)@(?<domain>.*)?$ 
+2
Jan 12 '15 at 19:55
source share

This works as for valid domain logins:

 var regex = @"^(.*\\)?([^\@]*)(@.*)?$"; var user = Regex.Replace("domain\\user", regex, "$2", RegexOptions.None); user = Regex.Replace("user@domain.com", regex, "$2", RegexOptions.None); 
+1
Aug 6 '14 at 19:34
source share

Piggy Bank on Derek Smalls Answers ...

 Regex.Replace(User.Identity.Name,@"^(?<domain>.*)\\(?<username>.*)|(?<username>[^\@]*)@(?<domain>.*)?$", "${username}", RegexOptions.None) 

worked for me.

0
Aug 12 '15 at 19:01
source share



All Articles