4

I'm devloping a C#/ASP.Net app and I'm trying to find a means of breaking down a URL into its component parts, then swapping out, or deleting these parts and creating a new URL.

For example if I have the following URL:

I'd like to split the URL down into:

  • Protocol (http, https, ftp, etc)
  • Domain (www.site.com)
  • Page (page.aspx)
  • URL parameters (parm1 = value1, parm2 = value2)

Once the URL is split down I'd like to manipulate each of the parts, for example:

  • add or remove parameters
  • change the value of parameters
  • change the page from page.aspx to page2.aspx

Then once I'm done create a new URL ready for use with the above changes.

I've checked out the MSDN documentation etc and can't find a utility class in .Net to take care of this. Any ideas?

Cheers, Steve

2 Answers 2

5

The framework comes with the UriBuilder class for this purpose.

It has get/set properties for the things you need:

  • Protocol: Scheme property
  • Domain: Host property
  • Page: Path property (will give you whole path, you might need to do some processing here).
  • Parameters: Query property (exposed as a string, you might need to do some processing on the string your self).

When you are done manipulating the UriBuilder, use the Uri property to get the result as a Uri object, or just ToString() if you just need the URL as a string.

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

Comments

1

Start by using UriBuilder (see driis's answer).

To parse the Query property use:

NameValueCollection q=HttpUtility.ParseQueryString(uri.Query);

You actually get an HttpValueCollection (internal) - so when you later call q.ToString() you'll get an url encoded query string back.

Since the class is internal you need to call

NameValueCollection q=HttpUtility.ParseQueryString("");

if you want to build the query string from scratch.

Comments

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.