How can I decode HTML characters in C#?

前端 未结 10 2028
夕颜
夕颜 2020-11-22 03:38

I have email addresses encoded with HTML character entities. Is there anything in .NET that can convert them to plain strings?

相关标签:
10条回答
  • 2020-11-22 03:38

    You can use HttpUtility.HtmlDecode

    If you are using .NET 4.0+ you can also use WebUtility.HtmlDecode which does not require an extra assembly reference as it is available in the System.Net namespace.

    0 讨论(0)
  • 2020-11-22 03:40

    Use Server.HtmlDecode to decode the HTML entities. If you want to escape the HTML, i.e. display the < and > character to the user, use Server.HtmlEncode.

    0 讨论(0)
  • 2020-11-22 03:45

    To decode HTML take a look below code

    string s = "Svendborg V&#230;rft A/S";
    string a = HttpUtility.HtmlDecode(s);
    Response.Write(a);
    

    Output is like

     Svendborg Værft A/S
    
    0 讨论(0)
  • 2020-11-22 03:45

    For .net 4.0

    Add a reference to System.net.dll to the project with using System.Net; then use the following extensions

    // Html encode/decode
        public static string HtmDecode(this string htmlEncodedString)
        {
            if(htmlEncodedString.Length > 0)
            {
                return System.Net.WebUtility.HtmlDecode(htmlEncodedString);
            }
            else
            {
                return htmlEncodedString;
            }
        }
    
        public static string HtmEncode(this string htmlDecodedString)
        {
            if(htmlDecodedString.Length > 0)
            {
                return System.Net.WebUtility.HtmlEncode(htmlDecodedString);
            }
            else
            {
                return htmlDecodedString;
            }
        }
    
    0 讨论(0)
  • 2020-11-22 03:47

    If there is no Server context (i.e your running offline), you can use HttpUtility.HtmlDecode.

    0 讨论(0)
  • 2020-11-22 03:47

    Write static a method into some utility class, which accept string as parameter and return the decoded html string.

    Include the using System.Web.HttpUtility into your class

    public static string HtmlEncode(string text)
        {
            if(text.length > 0){
    
               return HttpUtility.HtmlDecode(text);
            }else{
    
             return text;
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题