12

I have a link in this format:

http://user:[email protected]

How to get user and pass from this URL?

3
  • 5
    What have you actually tried? What was the expected result? If you didn't get the result you expected, what did you actually get? Sorry, this is not a "give me teh codez" site - please read the FAQ if that is unclear. Commented Feb 22, 2012 at 19:34
  • 3
    From the FAQ: "You should only ask practical, answerable questions based on actual problems that you face." and "We’re all here to learn together. Be tolerant of others who may not know everything you know." Commented Oct 25, 2012 at 17:48
  • Better question is how to remove it :P Commented Jan 10, 2015 at 6:23

2 Answers 2

20

Uri class has a UserInfo attribute.

Uri uriAddress = new Uri ("http://user:[email protected]/index.htm ");
Console.WriteLine(uriAddress.UserInfo);

The value returned by this property is usually in the format "userName:password".

http://msdn.microsoft.com/en-us/library/system.uri.userinfo.aspx

Sign up to request clarification or add additional context in comments.

3 Comments

This only works if there is NOT an "@" symbol in the credentials (common for usernames that are email addresses, or in strong passwords).
True. Note that '@' is a reserved character in the Uniform Resource Identifier, specified by the RFC. See tools.ietf.org/html/rfc3986#page-12 As you can see there are a lot of characters, when contained in a username or a password that make the URI invalid.
Yeah, when we did this, we ended up parsing out the credentials and using HttpUtility.UrlEncode on them before adding them back. Windows Explorer will accept un-encoded credentials (which is where our users are copying/pasting them into our app). Also, UriBuilder does not encode them when it builds the URI. I would expect a "builder" to handle things like that; it's annoying to have to parse stuff before passing it off to a parser. :)
6

I took this a little farther and wrote some URI extensions to split username and password. Wanted to share my solution.

public static class UriExtensions
{
    public static string GetUsername(this Uri uri)
    {
        if (uri == null || string.IsNullOrWhiteSpace(uri.UserInfo))
            return string.Empty;

        var items = uri.UserInfo.Split(new[] { ':' });
        return items.Length > 0 ? items[0] : string.Empty;
    }

    public static string GetPassword(this Uri uri)
    {
        if (uri == null || string.IsNullOrWhiteSpace(uri.UserInfo))
            return string.Empty;

        var items = uri.UserInfo.Split(new[] { ':' });
        return items.Length > 1 ? items[1] : string.Empty;
    }
}

2 Comments

Missed@ domain parsing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.