Search code examples
c#.neturi

Changing the port of the System.Uri


I have an Uri object which contains an address, something like http://localhost:1000/blah/blah/blah. I need to change the port number and leave all other parts of the address intact. Let's say I need it to be http://localhost:1080/blah/blah/blah.

The Uri objects are pretty much immutable, so I can access the port number through the Port property, but it's read-only. Is there any sane way to create an Uri object exactly like another but with different port? By "sane" I mean "without messing around with regular expressions and string manipulations" because while it's trivial for the example above, it still smells like a can of worms to me. If that's the only way, I really hope that it's already implemented by someone and there are some helpers out there maybe (I didn't find any though).


Solution

  • Have you considered the UriBuilder class?

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

    The UriBuilder class provides a convenient way to modify the contents of a Uri instance without creating a new Uri instance for each modification.

    The UriBuilder properties provide read/write access to the read-only Uri properties so that they can be modified.