HTML特殊字符之編碼、解碼

来源:互联网 发布:win10没有网络协议 编辑:程序博客网 时间:2024/06/06 01:32

string ss = string.ToHtmlEncode();

 

using System.Web;
 
namespace System
{
    /// <summary>
    /// Html Extension Methods
    /// </summary>
    public static class HtmlExtension
    {
        /// <summary>
        /// 字串轉換為HTML編碼的字串
        /// </summary>
        /// <param name="html">欲轉換為HTML編碼的字串</param>
        /// <returns>HTML編碼的字串</returns>
        public static string ToHtmlEncode(this Object html)
        {
            if (html != null)
            {
                string value = html.ToString();

                if (!value.IsEmpty())
                {
                    return HttpUtility.HtmlEncode(value).ReplaceNewLineToBR();
                }
            }
           
            return "";
        }

        /// <summary>
        /// 將HTML編碼的字串轉換為解碼的字串
        /// </summary>
        /// <param name="html">欲將HTML編碼的字串轉換為解碼的字串</param>
        /// <returns>解碼的字串</returns>
        public static string ToHtmlDecode(this Object html)
        {
            if (html != null)
            {
                string value = html.ToString();// as string;

                if (!value.IsEmpty())
                {
                    return HttpUtility.HtmlDecode(value.ReplaceBRToNewLine());
                }
            }
           
            return "";
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace System
{
    /// <summary>
    /// String Extension Methods
    /// </summary>
    public static class StringExtension
    {
        /// <summary>
        /// 判斷字串是否為空字串(Null或空字串)
        /// </summary>
        /// <param name="value">字串</param>
        /// <returns>若為空字串時回傳True,反之回傳False</returns>
        public static bool IsEmpty(this string value)
        {
            if (value == null)
            {
                return true;
            }

            return value.Trim().Length == 0;
        }

        /// <summary>
        /// 替換新行字串(Environment.NewLine)為HTML BR
        /// </summary>
        /// <param name="value">字串</param>
        /// <returns>替換新行字串為HTML BR</returns>
        public static string ReplaceNewLineToBR(this string value)
        {
            if (!value.IsEmpty())
            {
                return value.Replace(Environment.NewLine, "<br />");
            }

            return "";
        }

        /// <summary>
        /// 替換HTML BR為新行字串(Environment.NewLine)
        /// </summary>
        /// <param name="value">字串</param>
        /// <returns>替換HTML BR為新行字串</returns>
        public static string ReplaceBRToNewLine(this string value)
        {
            if (!value.IsEmpty())
            {
                return value.Replace("<br />", Environment.NewLine);
            }

            return "";
        }
    }
}

 

原创粉丝点击