Monday, 27 August 2012

.Net Tips, C# Tips : Parse and create URL with C# Examples and VB.Net Examples

There is always a need to parse and create valid URL.
We can achieve this using "Uri" class's "TryCreate" method.

Here is example for this.
In this example we take on URL string and parse that and create URI object from that.
If URL format in invalid than URL is not parsed and URI object is not created.
This method try to possible all way to create URI object.

If you do not specify "Scheme" in URL string than also this method create object but if you access "Scheme" property of this created object it will return error, so you need to handle this error. This is same for other properties also.

C# Examples :
        string strUri = "";
        Uri objUri = null;
        // Safely parse the url
        if (Uri.TryCreate(strUri, UriKind.RelativeOrAbsolute, out objUri))
            Response.Write("<b>Parsed URI : </b>" + objUri.OriginalString);
            Response.Write("<br/><b>Scheme : </b>" + objUri.Scheme);
            Response.Write("<br/><b>Host : </b>" + objUri.Host);
            Response.Write("<br/><b>Port : </b>" + objUri.Port);
            Response.Write("<br/><b>Path and Query : </b>" + objUri.PathAndQuery);
        } Examples :
        Dim strUri As String = ""
        Dim objUri As Uri
        '' Parse the url
        If (Uri.TryCreate(strUri, UriKind.RelativeOrAbsolute, objUri)) Then
            Response.Write("<b>Parsed URI : </b>" & objUri.OriginalString)
            Response.Write("<br/><b>Scheme : </b>" & objUri.Scheme)
            Response.Write("<br/><b>Host : </b>" & objUri.Host)
            Response.Write("<br/><b>Port : </b>" & objUri.Port)
            Response.Write("<br/><b>Path and Query : </b>" & objUri.PathAndQuery)
        End If

Output :

Click Here to view Examples of "Create a well formed URI using UriBuilder class with C# Examples and VB.Net Examples ". Click Here...

This type of .Net Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.

1 comment:

  1. Its very informative blog and useful article thank you for sharing with us , keep posting learn
    more about Dot NET Online Course Hyderabad