I have a string that I'd like to encode into the standard URL format. From what I've found, I should be able to do this via the httpUtility.urlEncode
method, but I don't seem to have that available.
I've added "using" references to both System.Web
and System.Net
to no avail. I've also seen other references to server.urlEncode amongst other variants, but I don't see the method anywhere.
I'm using the latest version of C# in Visual Studio 2010. Is the method called something different in this version, hidden somewhere else, or am I completely off base?
Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing into a URL.
UrlEncode(String, Encoding)Encodes a URL string using the specified encoding object. public: static System::String ^ UrlEncode(System::String ^ str, System::Text::Encoding ^ e); public: static System::String ^ UrlEncode(System::String ^ s, System::Text::Encoding ^ Enc); C# Copy.
UrlEncode is a convenient way to access the HttpUtility. UrlEncode method at run time from an ASP.NET application. Internally, UrlEncode uses HttpUtility. UrlEncode to encode strings. To encode or decode values outside of a web application, use the WebUtility class.
By default, new projects in Visual Studio 2010 target the .NET Framework 4.0 Client Profile, which does not include the System.Web
assembly.
You can change the version of the Framework that your project targets in your project's Properties. Under the "Application" tab, select ".NET Framework 4.0" from the combobox labeled "Target framework".
Then, make sure that you have added a reference to System.Web
using the "Add Reference" dialog.
Finally, add a using
directive to the top of your class for the System.Web
namespace:
using System.Web;
You'll find the various overloads of the UrlEncode
method in the HttpUtility
class. Sample code:
HttpUtility.UrlEncode("http://www.google.com/");
In .Net 4.5 you can (should?, 'please use' says a Katana comment) use the System.Net.WebUtility.UrlEncode method.
It can't be named differently since Visual Studio doesn't supply the class or method names, the .NET framework does.
All I can tell you is that the System.Web.HttpUtility AND System.Web.HttpServerUtility classes contain a method called UrlEncode(string)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With