1

I have some strings like this:

www.example.com/sdWqaP

twitter.com/sdfks

and want to assign them to a HyperLink

var hyperlink = new Hyperlink
{
   NavigateUri = new Uri(url),
   TargetName = "_blank",
};

if url starts with http:// it works fine, otherwise throws a UriFormatException.

Update: urls like this www.google.com aren't valid http urls. isn't there a better way than var url = "http://" + "www.google.com"

user3293835
  • 829
  • 2
  • 15
  • 30

3 Answers3

4

You can use

var uri = new UriBuilder(s).Uri;

Reference: http://msdn.microsoft.com/en-us/library/y868d5wh(v=vs.110).aspx

public UriBuilder(
    string uri
)
// If uri does not specify a scheme, the scheme defaults to "http:".
lastr2d2
  • 3,604
  • 2
  • 22
  • 37
1

Scheme (http:// in your case) is mandatory part of Uri string. UriFormatException will be thrown if the scheme specified in uri string is not correctly formed according to Uri.CheckSchemeName() method.

[MSDN : Uri Constructor (String)].

I don't understand well what you mean "better safer way". Appending scheme in uri string is common practice anyway.

har07
  • 88,338
  • 12
  • 84
  • 137
  • thanks @har07. my url strings may not have `http://` as in example, and my question is how to append that scheme? isn't there a better way than `var url = "http://" + "www.google.com"`? – user3293835 Mar 14 '14 at 06:27
1

Check your URL is valid and then assign to the URL

For validating a URL check the below link

How to check whether a string is a valid HTTP URL?

Community
  • 1
  • 1
Prasanth V J
  • 1,126
  • 14
  • 32