Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the port of the System.Uri

Tags:

c#

.net

uri

So I have this 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)

Thanks in advance.

like image 655
Dyppl Avatar asked May 26 '11 11:05

Dyppl


People also ask

How do I specify a port in URI?

To specify a different port, the port number follows host name and is separated from hostname by a colon. For example, http://somedomain.com:110 means access this host on port 110 instead of the default HTTP port 80. In this example, the host server is somedomain.com.

What is URI port?

The port number defines the protocol port used for contacting the server referenced in the URI. If a port is not specified as part of the URI, the Port property returns the default value for the protocol. If there is no default port number, this property returns -1.

What does URI mean in PowerShell?

#PSTip Working with a Uniform Resource Identifier (URI) in PowerShell.


2 Answers

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.

like image 57
jglouie Avatar answered Sep 19 '22 09:09

jglouie


I second a vote for UriBuilder. I actually have an extension method for changing the port of a URI:

public static class UriExtensions {     public static Uri SetPort(this Uri uri, int newPort) {         var builder = new UriBuilder(uri);         builder.Port = newPort;         return builder.Uri;     } } 

Usage:

var uri = new Uri("http://localhost:1000/blah/blah/blah"); uri = uri.SetPort(1337); // http://localhost:1337/blah/blah/blah 
like image 31
alexn Avatar answered Sep 19 '22 09:09

alexn