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.
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.
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.
#PSTip Working with a Uniform Resource Identifier (URI) in PowerShell.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With