Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse user credentials from URL in C#?

Tags:

c#

url

parsing

I have a link in this format:

http://user:[email protected]

How to get user and pass from this URL?

like image 780
BILL Avatar asked Feb 22 '12 19:02

BILL


2 Answers

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;
    }
}
like image 111
kampsj Avatar answered Nov 03 '22 02:11

kampsj


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

like image 35
supertopi Avatar answered Nov 03 '22 02:11

supertopi