I want to convert &
to &, "
to " etc.
Is there a function in c# that could do that without writing all the options manually?
Asked
Active
Viewed 1.2e+01k times
74

Matt Hamsmith
- 3,955
- 1
- 27
- 42
6 Answers
117
System.Web.HttpUtility.HtmlDecode()
Edit: Note from here that "To encode or decode values outside of a web application, use..."
System.Net.WebUtility.HtmlDecode()

Matt Hamsmith
- 3,955
- 1
- 27
- 42
-
3@AbuHamzah it should not work for & but it should work for & – Peter Apr 11 '14 at 07:00
-
2@BartoszWojcik This method has been around since .NET 1.1. See MSDN documentation: http://msdn.microsoft.com/en-us/library/aa332854%28v=vs.71%29.aspx – Matt Hamsmith Jun 14 '14 at 17:48
-
I use 4.7.1 but cant find `System.Web.HttpUtility.HtmlDecode()` – Rishav Jul 04 '18 at 22:36
-
1Rishav, we need to add reference to System.Web in order to use the function. – Nick_F Sep 04 '18 at 09:05
31
Use the static method
HttpUtility.HtmlEncode
to change &
to &
and "
to "
. Use
HttpUtility.HtmlDecode
to do the reverse.

Ian Kemp
- 28,293
- 19
- 112
- 138
21
You can use System.Net.WebUtility.HtmlDecode(uri);

Chris Barlow
- 3,274
- 4
- 31
- 52

Corredera Romain
- 256
- 2
- 4
-
1@AmirNo-Family If you are not in a web application, then yes, you need the System.Net.WebUtility version. Otherwise, System.Web.HttpUtility.HtmlDecode works just fine. – Matt Hamsmith Jul 06 '18 at 16:05
7
using System.Web;
...
var html = "this is a sample & string";
var decodedhtml = HttpUtility.HtmlDecode(html);
-
Although this code might (or might not) solve the problem, a good answer should explain what the code does and how it solves the problem. – BDL Oct 02 '18 at 08:05
4

RichardOD
- 28,883
- 9
- 61
- 81
-
1
-
I was assuming ASP.NET. The documentation mentions HttpUtility's HtmlDecode, as this is what Server.HtmlEncode calls anyway. Its easy to work this out by reading the documentation- Server.HtmlEncode's documentation actually explains what it does, unfortunately HttpUtility.HtmlDecode's doesn't. – RichardOD Oct 13 '09 at 19:29
-7
For .NET < 4 simple encoder
public static string HtmlEncode(string value)
{
return value.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("'", "'");
}

Bartosz Wójcik
- 1,079
- 2
- 13
- 31