Remove domain information from login id in C#

帅比萌擦擦* 提交于 2019-12-21 03:20:12

问题


I would like to remove the domain/computer information from a login id in C#. So, I would like to make either "Domain\me" or "Domain\me" just "me". I could always check for the existence of either, and use that as the index to start the substring...but I am looking for something more elegant and compact.

Worse case 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);

回答1:


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

use a 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);  

    }

}



回答2:


You could abuse the Path class, thusly:

string shortName = System.IO.Path.GetFileNameWithoutExtension(ResourceLoginName);



回答3:


How's about:

string shortName = ResourceLoginName.Split('\\')[1]



回答4:


This will work for both but with named groups.

^(?<domain>.*)\\(?<username>.*)|(?<username>[^\@]*)@(?<domain>.*)?$



回答5:


I always do it this way:

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

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




回答6:


        string theString = "domain\\me";
        theString = theString.Split(new char[] { '\\' })[theString.Split(new char[] { '\\' }).Length - 1];



回答7:


This works for both 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);



回答8:


Piggy backing on Derek Smalls Answer...

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

worked for me.



来源:https://stackoverflow.com/questions/185559/remove-domain-information-from-login-id-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!