63

Normally I would just use:

HttpContext.Current.Server.UrlEncode("url");

But since this is a console application, HttpContext.Current is always going to be null.

Is there another method that does the same thing that I could use?

12 Answers 12

83

Try this!

Uri.EscapeUriString(url);

Or

Uri.EscapeDataString(data)

No need to reference System.Web.

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

5
  • Not sure why this was down-voted; maybe the edit fixed something? Anyhow, it's a good answer. For more info, see this answer from another, similar question.
    – Granger
    Commented Jul 16, 2012 at 18:01
  • Works great and you don't need to add any refference. Commented Oct 24, 2012 at 9:36
  • 2
    This is a far better answer, because you don't have to import new references to the console app, since the Uri class is in System. Commented Jan 28, 2014 at 13:26
  • 3
    This does not be the same as HttpUtility.UrlEncode while @KevinUK asked for Encode. Commented Mar 9, 2016 at 14:03
  • 1
    The results for this method are completely different to UrlEncode. There are several elements which will not be encoded correctly for a URL string (for example '+'. Either use HttpUtility.UrlEncode or Uri.EscapeDataString as explained very well here: stackoverflow.com/a/34189188/7391
    – Jason
    Commented Feb 15, 2018 at 10:56
71

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

4
  • 3
    I don't want to rain on everyone's parade, but the mentioned HttpUtility.UrlEncode doesn't seem to be visible even when I include "using System.Web". Does this actually work for someone and if so can you include the actual code? Commented Nov 5, 2008 at 19:07
  • 26
    You need (must) add System.Web as a reference. Simply putting using System.Web is not enough
    – Anjisan
    Commented Mar 16, 2009 at 15:02
  • I knew about System.Web.HttpContext but it wasn't resolving. Thanks Anjisan for pointing out that I needed to add System.Web as a reference. +1 from me!
    – Jere.Jones
    Commented Aug 28, 2009 at 1:24
  • 1
    Problem is you will get something like this: The referenced assembly ".." could not be resolved because it has a dependency on "System.Web ...". Two options - either change the target framework to not use the client profile, or use the C# example given by t3rse elsewhere on this page. Commented Nov 21, 2011 at 21:21
13

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));
    }
}
1
  • 1
    Great work both t3rse and Ian Hopkins. I ran into this issue building a wpf application. wpf uses the slimmed down 'client profile' of .net while my class library was using the full version. Only the full version of .net has access to System.Web which contains HttpUtility.UrlEncode.
    – MrSharps
    Commented Jan 2, 2012 at 3:44
7

Add using System.Net; then use: WebUtility.UrlDecode(string)
or Fully-Qualify: System.Net.WebUtility.UrlDecode(string)

No need to add any additional References.
The WebUtility is included (by Default) in System (under the "References" Project Folder).

1
  • 2
    Good to mention this method is available since .NET 4.0. Commented Jan 31, 2016 at 8:09
6

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.

4

Try using the UrlEncode method in the HttpUtility class.

  1. http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx
3

I ran into this problem myself, and rather than add the System.Web assembly to my project, I wrote a class for encoding/decoding URLs (its pretty simple, and I've done some testing, but not a lot). I've included the source code below. Please: leave the comment at the top if you reuse this, don't blame me if it breaks, learn from the code.

''' <summary>
''' URL encoding class.  Note: use at your own risk.
''' Written by: Ian Hopkins (http://www.lucidhelix.com)
''' Date: 2008-Dec-23
''' </summary>
Public Class UrlHelper
    Public Shared Function Encode(ByVal str As String) As String
        Dim charClass = String.Format("0-9a-zA-Z{0}", Regex.Escape("-_.!~*'()"))
        Dim pattern = String.Format("[^{0}]", charClass)
        Dim evaluator As New MatchEvaluator(AddressOf EncodeEvaluator)

        ' replace the encoded characters
        Return Regex.Replace(str, pattern, evaluator)
    End Function

    Private Shared Function EncodeEvaluator(ByVal match As Match) As String
    ' Replace the " "s with "+"s
        If (match.Value = " ") Then
            Return "+"
        End If
        Return String.Format("%{0:X2}", Convert.ToInt32(match.Value.Chars(0)))
    End Function

    Public Shared Function Decode(ByVal str As String) As String
        Dim evaluator As New MatchEvaluator(AddressOf DecodeEvaluator)

        ' Replace the "+"s with " "s
        str = str.Replace("+"c, " "c)

        ' Replace the encoded characters
        Return Regex.Replace(str, "%[0-9a-zA-Z][0-9a-zA-Z]", evaluator)
    End Function

    Private Shared Function DecodeEvaluator(ByVal match As Match) As String
        Return "" + Convert.ToChar(Integer.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber))
    End Function
End Class
2
  • 3
    downvoted... writing your own code so you can avoid a reference to a standard lib that doesn't write is "A Bad Thing" typically. Commented Sep 1, 2011 at 15:18
  • I have to agree with Justin here
    – Aaron M
    Commented Oct 14, 2011 at 18:38
2

Kibbee offers the real answer. Yes, HttpUtility.UrlEncode is the right method to use, but it will not be available by default for a console application. You must add a reference to System.Web. To do that,

  1. In your solution explorer, right click on references
  2. Choose "add reference"
  3. In the "Add Reference" dialog box, use the .NET tab
  4. Scroll down to System.Web, select that, and hit ok

NOW you can use the UrlEncode method. You'll still want to add,

using System.Web

at the top of your console app or use the full namespace when calling the method,

System.Web.HttpUtility.UrlEncode(someString)

1

HttpUtility.UrlEncode("url") in System.Web.

1

use the static HttpUtility.UrlEncode method.

0

Best thing is to Add Reference to System.web..dll

and use var EncodedUrl=System.Web.HttpUtility.UrlEncode("URL_TEXT");

You can find the File at System.web.dll

0

Uri.EscapeUriString should not be used for escaping a string to be passed in a URL as it does not encode all characters as you might expect. The '+' is a good example which is not escaped. This then gets converted to a space in the URL since this is what it means in a simple URI. Obviously that causes massive issues the minute you try and pass something like a base 64 encoded string in the URL and spaces appear all over your string at the receiving end.

You can use HttpUtility.UrlEncode and add the required references to your project (and if you're communicating with a web application then I see no reason why you shouldn't do this).

Alternatively use Uri.EscapeDataString over Uri.EscapeUriString as explained very well here: https://stackoverflow.com/a/34189188/7391

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.