Friday, November 21, 2008

Validating URIs in C#

I wanted to share a quick tip on how to validate if a given URI is well formed. Normally this will work in the case you want to make sure the URI you are passing is well formed, although it won't validate if the URI is not broken. This is very useful for making URI validations, especially when you are working with Silverlight image controls when setting the sources by code.

Let's say we are receiving the uriString as a parameter and we want to assign that string URI to an image control's source property. What we need to use is the Uri.IsWellFormedUriString(string uriString, UriKind uriKind) which will check that the URI is well formed and that it doesn't required further scaping:

public void SetImageSource(String uriString)
if (Uri.IsWellFormedUriString(uriString, UriKind.Absolute))
this.Thumbnail.Source = new BitmapImage(new Uri(uriString));

Then you can use the "else" block to set the thubmnail image of our control to a default well formed URI.

Hope it is useful for you.


  1. Thanks. The Uri class can be our friend once again. I've been using the Uri class - but must have not noticed this method for validation.


  2. Thanks..I have googled on various sites but I like your post the most. It is simple and to the point.