Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

c# - Add scheme to URL if needed

To create a Uri from a string you can do this:

Uri u = new Uri("example.com");

But the problem is if the string (like the one above) doesn't contain the protocol you will get an exception: "Invalid URI: The format of the URI could not be determined."

To avoid the exception you should secure the string includes a protocol, like below:

Uri u = new Uri("http://example.com");

But if you take the url as input, how can you add the protocol if it's missing?
I mean apart from some IndexOf/Substring manipulation?

Something elegant and fast?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could also use UriBuilder:

public static Uri GetUri(this string s)
{
    return new UriBuilder(s).Uri;
}

Remarks from MSDN:

This constructor initializes a new instance of the UriBuilder class with the Fragment, Host, Path, Port, Query, Scheme, and Uri properties set as specified in uri.

If uri does not specify a scheme, the scheme defaults to "http:".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...