UrlEncode through a console application?

Solution 1:

Try this!

Uri.EscapeUriString(url);

Or

Uri.EscapeDataString(data)

No need to reference System.Web.

Edit: Please see another SO answer for more...

Solution 2:

I'm not a .NET guy, but, can't you use:

HttpUtility.UrlEncode Method (String)

Which is described here:

HttpUtility.UrlEncode Method (String) on MSDN

Solution 3:

The code from Ian Hopkins does the trick for me without having to add a reference to System.Web. Here is a port to C# for those who are not using VB.NET:

/// <summary>
/// URL encoding class.  Note: use at your own risk.
/// Written by: Ian Hopkins (http://www.lucidhelix.com)
/// Date: 2008-Dec-23
/// (Ported to C# by t3rse (http://www.t3rse.com))
/// </summary>
public class UrlHelper
{
    public static string Encode(string str) {
        var charClass = String.Format("0-9a-zA-Z{0}", Regex.Escape("-_.!~*'()"));
        return Regex.Replace(str, 
            String.Format("[^{0}]", charClass),
            new MatchEvaluator(EncodeEvaluator));
    }

    public static string EncodeEvaluator(Match match)
    {
        return (match.Value == " ")?"+" : String.Format("%{0:X2}", Convert.ToInt32(match.Value[0]));
    }

    public static string DecodeEvaluator(Match match) {
        return Convert.ToChar(int.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber)).ToString();
    }

    public static string Decode(string str) 
    {
        return Regex.Replace(str.Replace('+', ' '), "%[0-9a-zA-Z][0-9a-zA-Z]", new MatchEvaluator(DecodeEvaluator));
    }
}

Solution 4:

You'll want to use

System.Web.HttpUtility.urlencode("url")

Make sure you have system.web as one of the references in your project. I don't think it's included as a reference by default in console applications.