Thursday, March 29, 2012

Encoding and Decoding URI and HTML strings using the .Net 4 ClientProfile

Thursday, March 29, 2012 Posted by Andre Broers , , , , , 6 comments
Before .Net version 4 we had to use the ASP.NET Full .Net Profile to do the above. Now we can do the encoding and decoding with the .Net Client Profile using the System.Net.WebUtility and the System.Uri classes.

Encoding and Decoding Uri strings


Say you have the following uri http://www.watzdprice.com/en/Home/ChangeLocation?LocReturnUrl=%2FProduct%2FDetails%2F1%2Feuro-95-petrol-1-liter and you want to decode and encode it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UriCode
{
    class Program
    {
        static void Main(string[] args)
        {
            string uri = @"http://www.watzdprice.com/en/Home/ChangeLocation?LocReturnUrl=%2FProduct%2FDetails%2F1%2Feuro-95-petrol-1-liter";
            Console.WriteLine(uri);
            Console.WriteLine(System.Uri.UnescapeDataString(uri));
            Console.WriteLine(System.Uri.EscapeDataString(System.Uri.UnescapeDataString(uri)));
            Console.ReadLine();
        }
    }
}

Will give the following result:
http://www.watzdprice.com/en/Home/ChangeLocation?LocReturnUrl=%2FProduct%2FDetails%2F1%2Feuro-95-petrol-1-liter
http://www.watzdprice.com/en/Home/ChangeLocation?LocReturnUrl=/Product/Details/1/euro-95-petrol-1-liter
http%3A%2F%2Fwww.watzdprice.com%2Fen%2FHome%2FChangeLocation%3FLocReturnUrl%3D%2FProduct%2FDetails%2F1%2Feuro-95-petrol-1-liter

Encoding and Decoding Html strings


Html is encoded en encoded a different way. Let's do the same example but than with a html string instead of a uri string.
<a href="http://www.getsentiment.com">Get Twitter Sentiment</a>

First the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HtmlCode
{
    class Program
    {
        static void Main(string[] args)
        {
            string html = @"<a href='http://www.getsentiment.com'>Get Twitter Sentiment</a>";
            Console.WriteLine(html);
            Console.WriteLine(System.Net.WebUtility.HtmlEncode(html));
            Console.WriteLine(System.Net.WebUtility.HtmlDecode(System.Net.WebUtility.HtmlEncode(html)));
            Console.ReadLine();
        }
    }
}


With the outcome:
<a href='http://www.getsentiment.com'>Get Twitter Sentiment</a>
&lt;a href=&#39;http://www.getsentiment.com&#39;&gt;Get Twitter Sentiment&lt;/agt;
<a href='http://www.getsentiment.com'>Get Twitter Sentiment</a>

6 comments: