Let’s say you have a whole bunch of Urls in a database or whatever collection format, but some are like these examples:
Is there an easy way to handle these variety of formats in C#?
Yes, we’ll do some prefix detection and then use a Uri class to help parse the data.
First, we assume our original data is in the HomePage variable on the Record object. We’ll detect if HomePage starts with “http://”. If it doesn’t, we’ll add that:
Record.HomePage = HTTP_PREFIX + Record.HomePage;
Next, we’ll try to parse the HomePage with the Uri class like this:
Uri myUri = new Uri(Record.HomePage);
catch (Exception e)
// HomePage is not parsable as Uri object
If HomePage is still in a bad format, the Uri constructor will throw an exception that we want to catch.
Record.Domain = myUri.Host;