74

I want to convert & to &, " to " etc. Is there a function in c# that could do that without writing all the options manually?

Matt Hamsmith
  • 3,955
  • 1
  • 27
  • 42

6 Answers6

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
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
  • 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);
BDL
  • 21,052
  • 22
  • 49
  • 55
Alex W.
  • 546
  • 1
  • 7
  • 22
  • 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

Server.HtmlDecode.

RichardOD
  • 28,883
  • 9
  • 61
  • 81
  • 1
    This works in ASP.NET. But otherwise, Matt's answer is better. – M4N Oct 13 '09 at 19:25
  • 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("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
    }
Bartosz Wójcik
  • 1,079
  • 2
  • 13
  • 31