I am currently working on a project with .NET 1.1 framework and I am stuck at this point. I have a string like \"http://www.example.com/mypage/default.aspx\" or it might be \"ht
Just create an extension to the Uri class. In my opinion things that should be there from the start. It will make your life easier.
public static class UriExtensions
{
public static Uri AttachParameters(this Uri uri,
NameValueCollection parameters)
{
var stringBuilder = new StringBuilder();
string str = "?";
for (int index = 0; index < parameters.Count; ++index)
{
stringBuilder.Append(str +
System.Net.WebUtility.UrlEncode(parameters.AllKeys[index]) +
"=" + System.Net.WebUtility.UrlEncode(parameters[index]));
str = "&";
}
return new Uri(uri + stringBuilder.ToString());
}
public static string GetBaseUrl(this Uri uri) {
string baseUrl = uri.Scheme + "://" + uri.Host;
return baseUrl;
}
public static string GetBaseUrl_Path(this Uri uri) {
string baseUrl = uri.Scheme + "://" + uri.Host + uri.AbsolutePath;
return baseUrl;
}
}
Usage:
//url - https://example.com/api/rest/example?firstname=Linus&lastname=Trovalds
Uri myUri = new Uri("https://example.com/api/rest/example").AttachParameters(
new NameValueCollection
{
{"firstname","Linus"},
{"lastname","Trovalds"}
}
);
// https://example.com
string baseUrl = myUri.GetBaseUrl();
// https://example.com/api/rest/example
string baseUrlandPath = myUri.GetBaseUrl_Path();