C#中实现UrlEncode和UrlDecode

时间:2023-03-09 17:04:57
C#中实现UrlEncode和UrlDecode
  • 有时需要进行url编码、解码,比如从html中捞数据,有可能>、&等字符会被编码成>等。
  • WinForm中默认没有引入System.Web,因此要现在项目中引入依赖
    • System.Web.HttpUtility.HtmlEncode(str);
    • System.Web.HttpUtility.HtmlDecode(str);
    • System.Web.HttpUtility.UrlEncode(str);
    • System.Web.HttpUtility.UrlDecode(str);
  • 编码、解码时可以指定编码,否则会看到乱码,如:
    • System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.Unicode);
    • System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.UTF8);
    • System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.GetEncoding( "GB2312 "));
    • System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.Unicode);
    • System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.UTF8);
    • System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.GetEncoding( "GB2312 "));