24

I'm trying to encode a URL using the HttpUtility.UrlEncode() method, why am I getting

The type or namespace name 'HttpUtility' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)

error ? I'm using Visual C# 2008, Express Edition.

The code I'm using is simplistic:

using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
namespace Lincr
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void cmdShorten_Click(object sender, EventArgs e)
        {
            WebRequest wrURL;
            Stream objStream;
            wrURL = WebRequest.Create("http://lin.cr?l=" + System.Web.HttpUtility.UrlEncode(txtURL.Text) + "&mode=api&full=1");
            objStream = wrURL.GetResponse().GetResponseStream();
            StreamReader objSReader = new StreamReader(objStream);
            textBox1.Text = objSReader.ReadToEnd().ToString();

        }

    }
}
Sathyajith Bhat
  • 21,321
  • 22
  • 95
  • 134

4 Answers4

33

You need to include a reference to System.Web. Right-click your project in the Solution Explorer and choose Add Reference... . If you take a look at MSDN you'll see it's contained in the System.Web.dll assembly, as far as I remember, this is not referenced by default in new projects.

Cecil Has a Name
  • 4,962
  • 1
  • 29
  • 31
29

Just in case anyone stumbles across this, is running VS 2010 and cannot find System.Web in the available references...

Right click on the project and select Properties, if the Target Framework is set to ".Net Framework 4 Client" then change it to ".Net Framework 4".

But beware this will close, reopen and rebuild your project (also if you have a web service references these will need to be refreshed)

earcam
  • 6,662
  • 4
  • 37
  • 57
  • 2
    +1 Thanks. I don't normally use Express, so I was wondering why I couldn't find this reference. – kervin Jun 29 '11 at 21:44
  • Thank you! I thought I was missing something obvious. – MrZander May 24 '13 at 19:18
  • Spot on the vs restart thing! – Wajih Jul 21 '14 at 07:17
  • For Visual Basic users, the Framework should be changed from the "Compile" tab, in "Advanced Compile Options", at the bottom of the "Compile" tab. https://msdn.microsoft.com/en-us/library/vstudio/bb398202(v=vs.100).aspx – Pek Ifly Aug 15 '15 at 07:41
5

For people using .NET 4.0 or later, you can use WebUtility.UrlEncode which works with client profile (does not require System.Web assembly reference).

Lirrik
  • 795
  • 11
  • 17
  • I am having to use .NET 4.0 for one project, and only HtmlEncode and HtmlDecode are available on WebUtility. There is no UrlEncode on the full profile. – Daniel Sep 04 '20 at 18:29
0
  1. click on project tab in menu
  2. click on Add References
  3. in References window click on Framework and check the System.Web
Adiii
  • 54,482
  • 7
  • 145
  • 148