views:

45

answers:

2

I have a issue when I look up a user name using the code below if the user has \v in their name. For Example, if their user name is xxx\vtest, it can't find the backslash when using the LastIndexOf function.

string strUser = this.Context.User.Identity.Name;
strUser = strUser.Substring(strUser.LastIndexOf("\\") + 1);

If I do try this, it works with no problems.

string strUser = @"xxx\vtest";
strUser = strUser.Substring(strUser.LastIndexOf("\\") + 1);

Any ideas on how to ignore the escape character while using User.Identity.Name?

+1  A: 

If the name has 'backslash v' you should find a backslash, if the name has a vertical tab (escaped '\v') you will not find a backslash. The reason you find a backslash in the second version is because you used an @ with the string declaration more info.

try this:

string strUser = this.Context.User.Identity.Name;
strUser = strUser.Substring(strUser.LastIndexOf("\v") + 1);

EDITED

If you know which escape characters you are looking for you can also use this:

string strUser = this.Context.User.Identity.Name;
strUser = strUser.Substring(strUser.LastIndexOfAny(new char[]{'\b','\t','\n','\v','\f','\r','\\'}) + 1);

If you know that there is exactly one character that follows the domain you can also use Regex to get the user.

string strUser = this.Context.User.Identity.Name;
strUser = Regex.Replace(strUser, @"^(xxx).(.+)$", "$2");
// or
strUser = Regex.Replace(strUser, @"^([a-zA-Z]*?)[^a-zA-Z](.+)$", "$2");
// or
strUser = Regex.Replace(strUser, @"^(.*?)[\t\n\v\f\r\\/<> ,.@](.+)$", "$2");
// it all depends on your input
Andre Haverdings
What if the name could have other characters other "\v" or another escape character in it?
Jeff
I edited my answer.. I think Regex is the best way to go, because you can put restrictions on parts of your input, but that just my personal opinion
Andre Haverdings
A: 

I ended up using System.Environment.UserName instead of Identity.Name. This way I didn't need to get the substring.

Jeff