Uri. In VB.NET programs, we often need to create and store URIs, or URLs, to remote resources like web servers. This can be done with the Uri and UriBuilder Classes.
To test if a URL is valid, we can use the Uri.TryCreate method. This tester-doer method returns True if the string can be parsed as a URL.
Example. One benefit to storing URLs in Uri objects is that we can access properties on the Uri. These properties can return important parts like the Host or the Scheme (like http).
Tip With a Uri object instance, we do not need to parse parts of the Uri ourselves. We can use helper functions to access the URI parts.
TryCreate. Is a String a valid URL? We can determine this with Uri.TryCreate, and as a bonus we can get the constructed Uri object as a return parameter.
Module Module1
Sub Main()
' Part 1: use Uri.TryCreate on valid url.
Dim uri1 As Uri = Nothing
If Uri.TryCreate("http://www.dotnetperls.com/", UriKind.Absolute, uri1)
Console.WriteLine("1 = {0}", uri1)
End If
' Part 2: handle an invalid Url with Uri.TryCreate.
Dim uri2 As Uri = Nothing
If Uri.TryCreate("http:dotnetperls-com", UriKind.Absolute, uri2)
Console.WriteLine("2 = {0}", uri2) ' Not reached.
End If
End Sub
End Module1 = http://www.dotnetperls.com/
UriBuilder. It is sometimes better to create a Uri object by using the UriBuilder Class. We can set parts like the Host, Path, and Scheme to modify the returned URL.
Tip The UriBuilder handles the syntax of the Uri scheme, such as the path separator and the scheme delimiter.
Module Module1
Sub Main()
' Use UriBuilder constructor.
Dim u1 As UriBuilder = New UriBuilder("http", "www.dotnetperls.com")
Console.WriteLine($"UriBuilder: {u1}")
' Use UriBuilder properties.
Dim u2 As UriBuilder = New UriBuilder()
u2.Host = "www.dotnetperls.com"
u2.Path = "uribuilder"
u2.Scheme = "http"
Console.WriteLine($"UriBuilder: {u2}")
' Convert to Uri.
Dim uri As Uri = u2.Uri
Console.WriteLine($" Uri: {uri}")
End Sub
End ModuleUriBuilder: http://www.dotnetperls.com/
UriBuilder: http://www.dotnetperls.com/uribuilder
Uri: http://www.dotnetperls.com/uribuilder
Summary. For complex VB.NET programs, using Uri and UriBuilder to manage URLs is a good idea as it can reduce possible syntax bugs in the resulting URLs. It can lead to more robust programs.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.