views:

1395

answers:

4

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

Thanks in advance.

A: 

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.

BoltBait
+1  A: 
        string theString = "domain\\me";
        theString = theString.Split(new char[] { '\\' })[theString.Split(new char[] { '\\' }).Length - 1];
Matt Dawdy
Yep, that's how I do it too with the addition of BoltBait's conversion to lower, because it's always helpful to have the usernames in a "controlled" casing (if using them as indexer keys for instance.
Kevin Dostalek
Good point, Kevin. I also figured that speed was definitely not an issue in this case, hence the multiple calls to split, etc. Makes for ugly code, but...
Matt Dawdy
+6  A: 

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

    }

}
Excellent point; using RegEx is a much more elegant solution.
Dan
+4  A: 

You could abuse the Path class, thusly:

string shortName = System.IO.Path.GetFileNameWithoutExtension(ResourceLoginName);
Jeffrey L Whitledge
Nice, that's clever.
Pete