Reputation: 4869
I have a link in this format:
http://user:[email protected]
How to get user
and pass
from this URL?
Upvotes: 12
Views: 8641
Reputation: 3149
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;
}
}
Upvotes: 6
Reputation: 3488
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
Upvotes: 20