简体   繁体   中英

Changing the port of the System.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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM