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


当前回答

值得一提的是,如果你像我一样使用HtmlAgilityPack,你应该使用HtmlAgilityPack. htmlentity . deentialize()。它接受一个字符串并返回一个字符串。

其他回答

值得一提的是,如果你像我一样使用HtmlAgilityPack,你应该使用HtmlAgilityPack. htmlentity . deentialize()。它接受一个字符串并返回一个字符串。

正如@CQ所说,您需要使用HttpUtility。HtmlDecode,但是默认情况下它在非asp . net项目中不可用。

对于非asp . net应用程序,需要添加对System.Web.dll的引用。在解决方案资源管理器中右键单击项目,选择“添加引用”,然后浏览列表中的System.Web.dll。

现在已经添加了引用,您应该能够使用完全限定名System. web . httputiliti . htmldecode访问方法,或者为System插入using语句。Web使事情变得更容易。

你可以使用HttpUtility。HtmlDecode

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

对于包含&#x20的字符串;我必须对字符串进行双重解码。第一次解码将把它转换成第二遍将正确地解码为预期的字符。

对于。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;
        }
    }