Tutorial :IndexOf function



Question:

I have this below code which will fetch loggedin UserID

System.Security.Principal.WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;          //networkID=User.          string strName = p.Identity.Name;          int start;          start = strName.IndexOf("\") + 1 ;       strName = strName.Substring(start, strName.Length - start);  

But start = strName.IndexOf("\") + 1 ; throwing out error saying Newline in constant. The logged in username I get is domainName\username and I want to use only username. Please help


Solution:1

Try IndexOf(@"\") or IndexOf("\\").


Solution:2

\ is an escape character - you must use either "\\" or @"\" to get this to work.


Solution:3

You have to escape your backslashes by doubling them:

start = strName.IndexOf("\\") + 1 ;   


Solution:4

Your backslash is escaping your last quote. use a double backslash to escape your backslash.

start = strName.IndexOf("\\") + 1 ;   


Solution:5

\ is an escape character. You either need to escape it with another \ or use verbatim string literals:

start = strName.IndexOf("\\") + 1 ;  

Or:

start = strName.IndexOf(@"\") + 1 ;  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »