我有用HTML字符实体编码的电子邮件地址。.NET中有什么东西可以将它们转换为普通字符串吗?


当前回答

对于。net 4.0

在项目中添加System.net.dll的引用,使用System.Net;然后使用以下扩展

// 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;
        }
    }

其他回答

你可以使用HttpUtility。HtmlDecode

如果你使用的是。net 4.0+,你也可以使用WebUtility。HtmlDecode不需要额外的程序集引用,因为它在系统中可用。网络名称空间。

使用服务器。HtmlDecode解码HTML实体。如果你想转义HTML,即显示<和>字符给用户,使用Server.HtmlEncode。

将static方法写入某个实用程序类,该实用程序类接受string作为参数并返回解码后的html字符串。

在你的类中包含使用System.Web.HttpUtility

public static string HtmlEncode(string text)
    {
        if(text.length > 0){

           return HttpUtility.HtmlDecode(text);
        }else{

         return text;
        }

    }

对于。net 4.0

在项目中添加System.net.dll的引用,使用System.Net;然后使用以下扩展

// 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;
        }
    }

如果没有服务器上下文(即离线运行),可以使用HttpUtility.HtmlDecode。