I am trying to substring but getting exception throwing.
my string "currentUserLogin" is uponet\\xyz
so what I want final result is xyz
string currentUser = currentUserLogin.Substring(currentUserLogin.LastIndexOf("'\'"));
I am trying to substring but getting exception throwing.
my string "currentUserLogin" is uponet\\xyz
so what I want final result is xyz
string currentUser = currentUserLogin.Substring(currentUserLogin.LastIndexOf("'\'"));
Try:
string currentUser = currentUserLogin.Substring(currentUserLogin.LastIndexOf("\\") + 1);
I should also point out that you will want some actual error handling. This will throw an IndexOutOfRangeException
if the \ comes at the very end of the string.
Relevant documentation: https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
Safer way to do it is to check if it is in the string first, or check if index > -1
.
int index = currentUserLogin.LastIndexOf('\\');
if (index > -1)
{
if (index + 1 == currentUserLogin)
{
currentUser = string.Empty;
}
else
{
currentUser = currentUserLogin.SubString(index + 1);
}
}
This here works like a charm
string currentUserLogin = "uponet\\xyz"; //Login
string[] currentUserParts = currentUserLogin.Split('\\');// splits in parts of [uponet],[],[xyz]
string currentUser = currentUserParts[currentUserParts.Count() - 1]; // get last from array
\ is a escape charector so by it standing a lone the compiler dont know what to do with it, the correct way to use e.g:
and so forth
Hope this helps :)