C#实现HttpUtility.UrlEncode输出大写字母
在C#中,HttpUtility.UrlEncode("www+mzwu+com")编码结果为www%2bmzwu%2bcom,由于一些服务器对大小写敏感,要求结果改为www%2Bmzwu%2Bcom,注意,不是WWW%2BMZWU%2BCOM。
一开始看到这需求,我的注意力就转移到怎么将www%2bmzwu%2bcom转为www%2Bmzwu%2Bcom,正则等方法马上浮现出来,最后发现,一开始思路就错了,舍本逐末,用HttpUtility.UrlEncode就可以搞定:
复制内容到剪贴板程序代码
public string UrlEncode(string str)
{
StringBuilder builder = new StringBuilder();
foreach (char c in str)
{
if (HttpUtility.UrlEncode(c.ToString()).Length > 1)
{
builder.Append(HttpUtility.UrlEncode(c.ToString()).ToUpper());
}
else
{
builder.Append(c);
}
}
return builder.ToString();
}
{
StringBuilder builder = new StringBuilder();
foreach (char c in str)
{
if (HttpUtility.UrlEncode(c.ToString()).Length > 1)
{
builder.Append(HttpUtility.UrlEncode(c.ToString()).ToUpper());
}
else
{
builder.Append(c);
}
}
return builder.ToString();
}